package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.controller.websocket.CabinetOpenServer;
import com.wing.cabinet.dao.CellInventoryInoutDao;
import com.wing.cabinet.dao.CellInventoryInoutDetailDao;
import com.wing.cabinet.dao.MailInfo;
import com.wing.cabinet.dao.StorageInventoryInoutDetailDao;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.*;
import com.wing.cabinet.model.response.*;
import com.wing.cabinet.utils.MailSenderConfig;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.constant.CabConstants;
import com.wing.order.model.entity.OrderReceiveLoad;
import com.wing.order.model.entity.OrderReceiveLoadDetail;
import com.wing.order.model.request.OrderReceiveLoadDetailForm;
import com.wing.order.model.request.OrderReceiveLoadForm;
import com.wing.order.service.CabInventoryProductService;
import com.wing.order.service.DynamicService;
import com.wing.order.service.OrderReceiveLoadDetailService;
import com.wing.order.service.OrderReceiveLoadService;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductPack;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.model.response.ProductPackVO;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductPackService;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.pulsar.client.api.PulsarClientException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 暂存柜存刀/取刀;存/取维修/回收刀明细-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
@Component
public class StorageInventoryInoutDetailServiceImpl extends ServiceImpl<StorageInventoryInoutDetailDao, StorageInventoryInoutDetail> implements StorageInventoryInoutDetailService {

    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;
    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private StorageInventoryInoutService inventoryInoutService;

    @Autowired
    private StorageInventoryProductService inventoryProductService;

    @Autowired
    private StorageInventorySpaceService inventorySpaceService;

    @Autowired
    private UseInventoryInoutDetailService useInventoryInoutDetailService;

    @Autowired
    private StorageSingleInventoryProductService storageSingleInventoryProductService;

    @Autowired
    private CabinetCargoSpaceService cargoSpaceService;

    @Autowired
    private StorageInventoryUncheckService inventoryUncheckService;
    @Autowired
    private EnterpricceIdService enterpricceIdService;

    @Autowired
    private StorageInventoryUserService inventoryUserService;


//    @Autowired
//    private StorageInventoryInoutService inventoryInoutService;

//    @Autowired
//    private StorageInventoryInoutDetailService storageInventoryInoutDetailService;

    @Autowired
    private CheckedInventoryInoutDetailService checkedInventoryInoutDetailService;

    @Autowired
    private CheckedResultService checkedResultService;

    @Autowired
    private CheckedResultDetailService checkedResultDetailService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private StorageInventoryCheckService storageInventoryCheckService;

    @Autowired
    private StorageInventoryCheckDetailService storageInventoryCheckDetailService;

    @Autowired
    private StorageInventoryCheckInoutService storageInventoryCheckInoutService;


    @Autowired
    private CabinetService cabinetService;


    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Autowired
    private UseInventoryUserKnifeService useInventoryUserKnifeService;

    @Autowired
    private UseInventoryUserKnifeSeqService useInventoryUserKnifeSeqService;

    @Autowired
    private UseInventoryUserKnifeInoutService useInventoryUserKnifeInoutService;

    @Autowired
    private StorageInventoryKnifeService storageInventoryKnifeService;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    @Autowired
    private CheckedResultLabelService checkedResultLabelService;

    @Autowired
    private UseInventoryKnifeService useInventoryKnifeService;

    @Autowired
    private OrderReceiveLoadService orderReceiveLoadService;

    @Autowired
    private OrderReceiveLoadDetailService orderReceiveLoadDetailService;

    @Autowired
    private CabInventoryProductService cabInventoryProductService;

    @Autowired
    private CellInventoryOutSeqService cellInventoryOutSeqService;

    @Autowired
    private CellInventoryInoutDao cellInventoryInoutDao;

    @Autowired
    private CellInventoryInoutDetailDao cellInventoryInoutDetailDao;

    @Autowired
    private ProductPackService productPackService;


    @Autowired
    private CabAlarmSettingsService cabAlarmSettingsService;

    @Autowired
    private StorageInventorySpaceService storageInventorySpaceService;

    @Autowired
    private UserClient userClient;
    @Resource
    private JavaMailSender javaMailSender;
    @Autowired
    private MailInfo mailInfo;
    @Autowired
    private CutterLifeCycleService cutterLifeCycleService;

    @Autowired
    MailSenderConfig senderConfig;

    @Override
    public int add(StorageInventoryInoutDetailForm storageInventoryInoutDetailForm) {

        //校验

        StorageInventoryInoutDetail storageInventoryInoutDetail = new StorageInventoryInoutDetail();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(StorageInventoryInoutDetail.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(storageInventoryInoutDetailForm, storageInventoryInoutDetail, copyOptions);

        return baseMapper.insert(storageInventoryInoutDetail);
    }

    @Override
    public List<StorageInventoryInoutDetailVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<StorageInventoryInoutDetailVO> pageList4app(Page page, Map<String, Object> params) {
        List<StorageInventoryInoutDetailVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public StorageInventoryInoutDetailVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public int update4Check(Integer businessTypeChecked, Long inoutId) {
        return baseMapper.update4Check(businessTypeChecked, inoutId);
    }

    BigDecimal getTotal(List<UseInventoryInoutDetailForm> list){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm:list){
            List<ProductDetail> productDetails=productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
            if (productDetails.size()>0&&productDetails.get(0).getMarketPrice()!=null){
                useInventoryInoutDetailForm.setPrice(productDetails.get(0).getMarketPrice());
                BigDecimal total=BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()).multiply(productDetails.get(0).getMarketPrice());
                useInventoryInoutDetailForm.setTotal(total);
                sum=sum.add(total);
            }
        }
        return sum;
    }
    BigDecimal getTotal2(List<StorageInventoryInoutDetailForm> list){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (StorageInventoryInoutDetailForm useInventoryInoutDetailForm:list){
            List<ProductDetail> productDetails=productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
            if (productDetails.size()>0&&productDetails.get(0).getMarketPrice()!=null){
                useInventoryInoutDetailForm.setPrice(productDetails.get(0).getMarketPrice());
                BigDecimal total=BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()).multiply(productDetails.get(0).getMarketPrice());
                useInventoryInoutDetailForm.setTotal(total);
                sum=sum.add(total);
            }
        }
        return sum;
    }



    BigDecimal getTotal(List<UseInventoryInoutDetailForm> list,StorageInventoryInout.OperationType operationType){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm:list){
            if (StorageInventoryInout.OperationType.in.equals(operationType)){
                List<UseInventoryKnife> skuInventoryKnifeList = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                if (skuInventoryKnifeList.size()>0){
                    useInventoryInoutDetailForm.setPrice(skuInventoryKnifeList.get(0).getPrice());
                    if (useInventoryInoutDetailForm.getPrice()!=null){
                        BigDecimal total=BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()).multiply(useInventoryInoutDetailForm.getPrice());
                        useInventoryInoutDetailForm.setTotal(total);
                        sum=sum.add(total);
                    }
                }

            }else if(StorageInventoryInout.OperationType.out.equals(operationType)){
                List<StorageInventoryKnife> skuInventoryKnifeList = storageInventoryKnifeService.list(new QueryWrapper<StorageInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                if (skuInventoryKnifeList.size()>0){
                    useInventoryInoutDetailForm.setPrice(skuInventoryKnifeList.get(0).getPrice());
                    if (useInventoryInoutDetailForm.getPrice()!=null){
                        BigDecimal total=BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()).multiply(useInventoryInoutDetailForm.getPrice());
                        useInventoryInoutDetailForm.setTotal(total);
                        sum=sum.add(total);
                    }

                }
            }

        }
        return sum;
    }
    BigDecimal getTotal2(List<StorageInventoryInoutDetailForm> list,StorageInventoryInout.OperationType operationType){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (StorageInventoryInoutDetailForm useInventoryInoutDetailForm:list){

            if (StorageInventoryInout.OperationType.in.equals(operationType)){
                List<UseInventoryKnife> skuInventoryKnifeList = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                if (skuInventoryKnifeList.size()>0){
                    useInventoryInoutDetailForm.setPrice(skuInventoryKnifeList.get(0).getPrice());
                    if (useInventoryInoutDetailForm.getPrice()!=null){
                        BigDecimal total=BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()).multiply(useInventoryInoutDetailForm.getPrice());
                        useInventoryInoutDetailForm.setTotal(total);
                        sum=sum.add(total);
                    }
                }
            }else if(StorageInventoryInout.OperationType.out.equals(operationType)){
                List<StorageInventoryKnife> skuInventoryKnifeList = storageInventoryKnifeService.list(new QueryWrapper<StorageInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                if (skuInventoryKnifeList.size()>0){
                    useInventoryInoutDetailForm.setPrice(skuInventoryKnifeList.get(0).getPrice());
                    if (useInventoryInoutDetailForm.getPrice()!=null){
                        BigDecimal total=BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()).multiply(useInventoryInoutDetailForm.getPrice());
                        useInventoryInoutDetailForm.setTotal(total);
                        sum=sum.add(total);
                    }

                }
            }

        }
        return sum;
    }

    @Override
    @Transactional
    public StorageInventoryInout inventoryIn(List<UseInventoryInoutDetailForm> list, StorageInventoryInout.BusinessType businessType, String deviceCode
            , StorageInventoryInout.BusinessDetailType businessDetailType,String remark) {

        if (StringUtils.isBlank(deviceCode)){
            deviceCode=list.get(0).getDeviceCode();
        }

        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long departmentId = JwtUtils.getDepartmentId();
        String departmentName = JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        String channelCode=JwtUtils.getChannelCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        String code = dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("IN-" + day + "-" + code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(JwtUtils.getLoginUserId());
        storageInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        storageInventoryInout.setCostCenter(JwtUtils.getCostCenter());
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.in);
        storageInventoryInout.setBusinessType(businessType);
        storageInventoryInout.setCompanyId(enterpriseId);
        storageInventoryInout.setDeviceCode(deviceCode);
        storageInventoryInout.setBusinessDetailType(businessDetailType);
        storageInventoryInout.setRemark(remark);
        if (StringUtils.isNotBlank(list.get(0).getRemark())){
            storageInventoryInout.setRemark(list.get(0).getRemark());
        }else{
            storageInventoryInout.setRemark(businessDetailType.getDesc());
        }
        storageInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        storageInventoryInout.setProcessId(list.get(0).getProcessId());
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setDepartmentName(departmentName);
        storageInventoryInout.setRoleName(roleName);
        storageInventoryInout.setEnterpriseCode(enterpriseCode);
        storageInventoryInout.setTotal(getTotal(list,storageInventoryInout.getOperationType()));
        storageInventoryInout.setChannelCode(channelCode);
        storageInventoryInout.setMainCabCode(list.get(0).getMainCabCode());
        storageInventoryInout.setRoleId(roleId);
        inventoryInoutService.save(storageInventoryInout);
        saveDetail(list, storageInventoryInout.getId(), UseInventoryInout.Type.in.name(), businessType, false, deviceCode, businessDetailType, null, null, null);
        useInventoryInoutDetailService.inventoryOut(list, storageInventoryInout.getId(), deviceCode, businessType, UseInventoryInout.Type.out, businessDetailType,remark);

        List<String> labelCodeList = new ArrayList<>();
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
            labelCodeList.add(useInventoryInoutDetailForm.getLabelCode());
        }
        // 添加刀具生命周期  --  暂存存入
        CutterLifeCycle.Status cutterLifeCycleStatus = null;
        if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempIn)){ // 暂存
            cutterLifeCycleStatus = CutterLifeCycle.Status.temporaryStorage;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairIn)){ // 报修
            cutterLifeCycleStatus = CutterLifeCycle.Status.repair;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleIn)){ // 报废
            cutterLifeCycleStatus = CutterLifeCycle.Status.scrap;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempInByOldNew)
                || businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairInByOldNew)
                || businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleInByOldNew)){ // 以旧换新
            cutterLifeCycleStatus = CutterLifeCycle.Status.tradeIn;
        }
        if(cutterLifeCycleStatus != null){
            cutterLifeCycleService.addLifeCycle(labelCodeList, cutterLifeCycleStatus, businessDetailType, null, storageInventoryInout.getCode(), deviceCode);
        }

//        StorageInventoryUncheck storageInventoryUncheck=new StorageInventoryUncheck();
//        storageInventoryUncheck.setInoutId(storageInventoryInout.getId());
//        inventoryUncheckService.save(storageInventoryUncheck);
        sendMsg(storageInventoryInout);
        return storageInventoryInout;
    }

    void sendMsg(StorageInventoryInout storageInventoryInout) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            syncDate(storageInventoryInout);
                        } catch (Exception e) {
                            log.error("syn fail", e);
                        }

                    }
                });
            }
        });
    }


    @Override
    @Transactional
    public void inventoryIn4Check(List<StorageInventoryInoutDetailForm> list, Long checkedResultId, StorageInventoryInout.BusinessType businessType, StorageInventoryInout.BusinessDetailType businessDetailType, StorageInventoryInout.BusinessTypePre businessTypePre, Long storageInventoryOutId, Long storageInventoryCheckId) {
        String departmentName = JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        Long departmentId=JwtUtils.getDepartmentId();
        String channelCode=JwtUtils.getChannelCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        String code = dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("IN-" + day + "-" + code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(JwtUtils.getLoginUserId());
        storageInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.in);
        storageInventoryInout.setBusinessType(businessType);
        storageInventoryInout.setStatus(StorageInventoryInout.Status.checked);
        storageInventoryInout.setCheckedResultId(checkedResultId);
        storageInventoryInout.setBusinessDetailType(businessDetailType);
        storageInventoryInout.setBusinessTypePre(businessTypePre);
        storageInventoryInout.setRemark(businessDetailType.getDesc());
        storageInventoryInout.setStorageInventoryOutId(storageInventoryOutId);
        storageInventoryInout.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        storageInventoryInout.setDepartmentName(departmentName);
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setRoleName(roleName);
        storageInventoryInout.setRoleId(roleId);
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setChannelCode(channelCode);
        inventoryInoutService.save(storageInventoryInout);
        List<UseInventoryInoutDetailForm> listIn = new ArrayList<>();
        for (StorageInventoryInoutDetailForm detailForm : list) {
            UseInventoryInoutDetailForm cellInventoryInoutDetailForm = new UseInventoryInoutDetailForm();
            BeanUtils.copyProperties(detailForm, cellInventoryInoutDetailForm);
            listIn.add(cellInventoryInoutDetailForm);
        }
        saveDetail(listIn, storageInventoryInout.getId(), UseInventoryInout.Type.in.name(), businessType, true, null, businessDetailType, checkedResultId, businessType, storageInventoryCheckId);
//        useInventoryInoutDetailService.inventoryOut(list,storageInventoryInout.getId());

    }

    @Override
    @Transactional
    public StorageInventoryInout inventoryOut(List<UseInventoryInoutDetailForm> list, StorageInventoryInout.BusinessType businessType, String deviceCode, StorageInventoryInout.BusinessDetailType businessDetailType,UseInventoryInout.BusinessType useBusinessType) {
//        setDefaultVal(list);
        if (StringUtils.isBlank(deviceCode)){
            deviceCode=list.get(0).getDeviceCode();
        }
        setDefaultVal4Out(list);
        String departmentName = JwtUtils.getDepartmentName();
        Long departmentId=JwtUtils.getDepartmentId();
        String channelCode=JwtUtils.getChannelCode();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        boolean warehouseInventoryFlag=false;
        if (systemRuleInfo!=null){
            warehouseInventoryFlag=systemRuleInfo.getWarehouseInventoryFlag();
        }

        if (warehouseInventoryFlag&&StorageInventoryInout.BusinessDetailType.newOut.equals(businessDetailType)){
            List<CellInventoryInoutDetailForm> listOut=new ArrayList<>();
            list.forEach(e->{
                CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
                BeanUtils.copyProperties(e,cellInventoryInoutDetailForm);
                listOut.add(cellInventoryInoutDetailForm);
            });
            cabInventoryProductService.inventoryOut(listOut);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        String code = dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("OU-" + day + "-" + code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(JwtUtils.getLoginUserId());
        storageInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.out);
        storageInventoryInout.setBusinessType(businessType);
        storageInventoryInout.setBusinessDetailType(businessDetailType);
        storageInventoryInout.setRemark(businessDetailType.getDesc());
        storageInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        storageInventoryInout.setProcessId(list.get(0).getProcessId());
        storageInventoryInout.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        storageInventoryInout.setDepartmentName(JwtUtils.getDepartmentName());
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setMainCabCode(list.get(0).getMainCabCode());
        storageInventoryInout.setRoleName(roleName);
        if (StorageInventoryInout.BusinessType.exhibit.equals(businessType)){
            storageInventoryInout.setTotal(getTotal(list));
        }else{
            storageInventoryInout.setTotal(getTotal(list,storageInventoryInout.getOperationType()));
        }
        storageInventoryInout.setDeviceCode(deviceCode);
        storageInventoryInout.setChannelCode(channelCode);
        storageInventoryInout.setRoleId(roleId);
        inventoryInoutService.save(storageInventoryInout);

        if (UseInventoryInout.BusinessType.tempOut.equals(useBusinessType)){
            saveDetail(list, storageInventoryInout.getId(), UseInventoryInout.Type.out.name(), businessType, false, deviceCode, businessDetailType, null, null, null);
            useInventoryInoutDetailService.inventoryIn4TempCabInventoryOut(list, storageInventoryInout.getId(), useBusinessType, deviceCode, businessDetailType, UseInventoryInout.Type.in);

            List<String> labelCodeList = new ArrayList<>();
            for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                labelCodeList.add(useInventoryInoutDetailForm.getLabelCode());
            }
            // 添加刀具生命周期  --  暂存取出
            cutterLifeCycleService.addLifeCycle(labelCodeList, CutterLifeCycle.Status.takeOut, businessDetailType, useBusinessType, storageInventoryInout.getCode(), deviceCode);
        }else if(UseInventoryInout.BusinessType.newOut.equals(useBusinessType)){
            saveDetail4NewOut(list, storageInventoryInout.getId(), UseInventoryInout.Type.out.name(), businessType, false, deviceCode, businessDetailType, null, null, null);
            List<CellInventoryInoutDetailForm> listOut=new ArrayList<>();
            list.forEach(e->{
                CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
                BeanUtils.copyProperties(e,cellInventoryInoutDetailForm);
                listOut.add(cellInventoryInoutDetailForm);
            });
            CellInventoryInout cellInventoryInout = saveCellInventoryInOut(deviceCode, CellInventoryInout.BusinessType.outByCabSpace, list, storageInventoryInout.getId());

            UseInventoryInout useInventoryInout=useInventoryInoutDetailService.inventoryIn(listOut,cellInventoryInout.getId(),useBusinessType,deviceCode,null,storageInventoryInout.getId(),storageInventoryInout.getId());
            storageInventoryInout.setLabelCodeList(useInventoryInout.getLabelCodeList());

            // 添加刀具生命周期  --  存刀柜领新
            List<String> labelCodeList = useInventoryUserKnifeService.listByParentCodes(useInventoryInout.getLabelCodeList());
            cutterLifeCycleService.addLifeCycle(labelCodeList, CutterLifeCycle.Status.getFresh, businessDetailType, useBusinessType, cellInventoryInout.getCode(), deviceCode);
        }else{
            throw new BusinessException("参数异常");
        }

        sendMsg(storageInventoryInout);

        //发送缺货告警邮件
        try {
            log.info("开始处理告警邮件发送,领取产品信息:{}",list);
            for (UseInventoryInoutDetailForm inoutDetailForm : list) {//领取产品
                String mainCabCode = inoutDetailForm.getMainCabCode();
                String cabCode = inoutDetailForm.getCabCode();
                String skuCode = inoutDetailForm.getSkuCode();

                QueryWrapper<CabAlarmSettings> queryWrapper =new QueryWrapper<>();
                queryWrapper.eq("cab_code",mainCabCode);
                queryWrapper.eq("sku_code",skuCode);
                CabAlarmSettings cabAlarmSettings = cabAlarmSettingsService.getOne(queryWrapper);
                log.info("物料告警信息:{}",cabAlarmSettings);

                Integer totalQuantity;//剩余库存总数
                Integer alarmSettingNum;//告警数量
                Integer lackQuantity;//缺货数量
                totalQuantity = storageInventorySpaceService.getSumByParams(mainCabCode,cabCode,skuCode);

                if (ObjectUtils.isNotEmpty(cabAlarmSettings)){
                    alarmSettingNum = cabAlarmSettings.getAlarmStock().intValue();

                    log.info("进入物料产品告警预值判断,告警数量:{},剩余库存总数:{}",alarmSettingNum,totalQuantity);
                    if (totalQuantity < alarmSettingNum) {
                        lackQuantity = (totalQuantity - alarmSettingNum) * -1;
                        log.info("缺货数量:{}",lackQuantity);
                        sendAlarmMail(alarmSettingNum,totalQuantity,lackQuantity,mainCabCode,cabCode,skuCode,JwtUtils.getEnterpriseName(),JwtUtils.getEnterpriseCode());
                    }
                } else {
                    alarmSettingNum = systemRuleInfo.getDefaultAlarmStock();

                    log.info("进入全局告警值预值判断,告警数量:{},剩余库存总数:{}",alarmSettingNum,totalQuantity);
                    if (totalQuantity < alarmSettingNum) {
                        lackQuantity = (totalQuantity - alarmSettingNum) * -1;
                        log.info("缺货数量:{}",lackQuantity);
                        sendAlarmMail(alarmSettingNum,totalQuantity,lackQuantity,mainCabCode,cabCode,skuCode,JwtUtils.getEnterpriseName(),JwtUtils.getEnterpriseCode());
                    }
                }

            }
        } catch (Exception e) {
            log.error("告警邮件发送失败：",e);
        } finally {
            return storageInventoryInout;
        }

    }

    public void sendAlarmMail(Integer alarmQuantity,Integer surplusQuantity,Integer lackQuantity,String mainCabCode,String cabCode,String skuCode,String enterpriseName,String enterpriseCode) throws Exception {
        log.info("----进入sendAlarmMail方法----,企业编号:{}",enterpriseCode);
//        executorService.submit(() -> {
//            try {
                emailWithPreview(alarmQuantity,surplusQuantity,lackQuantity,mainCabCode,cabCode,skuCode,enterpriseName,enterpriseCode);
//            } catch (Exception e) {
//                log.error("sendMail fail=>{}",e);
//            }
//        });
    }

    public void emailWithPreview(Integer alarmQuantity,Integer surplusQuantity,Integer lackQuantity,String mainCabCode,String cabCode,String skuCode,String enterpriseName,String enterpriseCode) throws Exception {
        log.info("进入emailWithPreview()，开始处理告警邮件信息 ");
//        DynamicDataSource.name.set(enterpriseCode.toLowerCase());

        HashMap map = mailInfo.queryInfo();
        String userName = map.get("send_account").toString();
        String password = map.get("email_password").toString();
        String host = map.get("smtp_server").toString();
        String port = map.get("port").toString();
        String ssl = map.get("is_ssl").toString();

        //查询主柜
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabCode, mainCabCode));

        // 库存告警管理员
        List<SystemRuleInfo> list = systemRuleInfoService.list();
        log.info("库存告警管理员信息:{}",list);

        if (CollectionUtil.isNotEmpty(list)) {
            if (StringUtils.isNotBlank(list.get(0).getInventoryManageUserId())) {
                String[] strId = list.get(0).getInventoryManageUserId().split(",");
                for (String item : strId) {
                    log.info("库存告警员ID:{}",item);
                    JsonResult<UserVO> userInfo = userClient.getUserInfo(Long.valueOf(item));

                    log.info("发送邮箱账号:{},密码:{}",userName,password);
                    log.info("告警员用户信息:{},用户邮箱:{}",userInfo,userInfo.getData().getEmail());
                    if (StringUtils.isNotBlank(userInfo.getData().getEmail())) {

                        StringBuffer content = new StringBuffer();
                        content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
                        content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
                        content.append("<p>公司名称为"+enterpriseName+"("+enterpriseCode+")"+"。</p>");
                        content.append("<p>主柜编号为"+mainCabCode+"。</p>");
                        content.append("<p>柜子编号为"+cabCode+"。</p>");
                        content.append("<p>物料编码为"+skuCode+"。</p>");
                        content.append("<p>告警设置数量为"+alarmQuantity+"（现剩余库存数量为"+surplusQuantity+"，缺货数量为"+lackQuantity+"）。</p>");
                        content.append("<p>主柜位置在"+cabinet.getWorkshopLocation()+"。</p>");
                        content.append("</div>");
                        content.append("</div>");
                        senderConfig.sendMail(userName,password,host,ssl, Integer.valueOf(port),userInfo.getData().getEmail(),"主题：缺货告警提醒",content.toString());

                        log.info("发送邮箱结束");
                    }
                }
            }
        }



    }

    private void setDefaultVal(OrderReceiveLoadForm orderReceiveLoadForm){
        if (orderReceiveLoadForm.getQuantityPackUnit()==null||orderReceiveLoadForm.getQuantityPackUnit()==0){
            orderReceiveLoadForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
        }
        if (orderReceiveLoadForm.getPackId()==null||orderReceiveLoadForm.getPackId()==0){
            orderReceiveLoadForm.setPackId(CabConstants.DEFAULT_PACK_ID);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getPackName())){
            orderReceiveLoadForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getUnitName())){
            orderReceiveLoadForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
        }
        if (CollectionUtil.isNotEmpty(orderReceiveLoadForm.getDetailList())){
            orderReceiveLoadForm.getDetailList().forEach(e->{
                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(CabConstants.DEFAULT_PACK_ID);
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(CabConstants.DEFAULT_PACK_NAME);
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                }
            });
        }
    }

    private void setDefaultValFromDb(OrderReceiveLoadForm orderReceiveLoadForm){
        ProductPackVO productPackVO ;
        if (orderReceiveLoadForm.getPackId()==null){
            productPackVO =productPackService.getDefaultPack();
        }else{
            productPackVO =productPackService.get4appById(orderReceiveLoadForm.getPackId());
        }
        //ProductPackVO productPackVO=productPackService.getDefaultPack();
        Integer quantityPackUnit=CabConstants.QUANTITY_PACK_UNIT;
        Long packId=CabConstants.DEFAULT_PACK_ID;
        String packName=CabConstants.DEFAULT_PACK_NAME;
        String unitName=CabConstants.DEFAULT_UNIT_NAME;
        if (productPackVO!=null){
            if (productPackVO.getBaseRate()!=null&&productPackVO.getBaseRate()!=0){
                quantityPackUnit=productPackVO.getBaseRate();
            }
            if (productPackVO.getId()!=null){
                packId=productPackVO.getId();
            }
            if (StringUtils.isNotBlank(productPackVO.getName())){
                packName=productPackVO.getName();
            }
            if (StringUtils.isNotBlank(productPackVO.getPackUnitName())){
                unitName=productPackVO.getPackUnitName();
            }
        }
        if (orderReceiveLoadForm.getQuantityPackUnit()==null||orderReceiveLoadForm.getQuantityPackUnit()==0){
            orderReceiveLoadForm.setQuantityPackUnit(quantityPackUnit);
        }
        if (orderReceiveLoadForm.getPackId()==null||orderReceiveLoadForm.getPackId()==0){
            orderReceiveLoadForm.setPackId(packId);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getPackName())){
            orderReceiveLoadForm.setPackName(packName);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getUnitName())){
            orderReceiveLoadForm.setUnitName(unitName);
        }
        if (CollectionUtil.isNotEmpty(orderReceiveLoadForm.getDetailList())){
            for (OrderReceiveLoadDetailForm e:orderReceiveLoadForm.getDetailList()){

                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(quantityPackUnit);
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(packId);
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(packName);
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(unitName);
                }
            }
        }

    }

    private void setDefaultVal(List<UseInventoryInoutDetailForm> list){
        if (CollectionUtil.isNotEmpty(list)){
            list.forEach(e->{
                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(CabConstants.DEFAULT_PACK_ID);
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(CabConstants.DEFAULT_PACK_NAME);
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                }
            });
        }
    }

    private void setDefaultVal4Check(List<StorageInventoryInoutDetailForm> list){
        if (CollectionUtil.isNotEmpty(list)){
            list.forEach(e->{
                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(CabConstants.DEFAULT_PACK_ID);
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(CabConstants.DEFAULT_PACK_NAME);
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                }
                e.setQuantityPack(e.getQuantityPackUnit());
            });
        }
    }

    private  void setDefaultVal4Out(List<UseInventoryInoutDetailForm> list){
        list.forEach(e->{
            List<StorageInventorySpace> cellInventorySpaces=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",e.getCabCode()).eq("space_code",e.getSpaceCode()));
            if (cellInventorySpaces.size()>0){

                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(cellInventorySpaces.get(0).getQuantityPackUnit());
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(cellInventorySpaces.get(0).getPackId());
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(cellInventorySpaces.get(0).getPackName());
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(cellInventorySpaces.get(0).getUnitName());
                }
            }
        });

    }

    @Override
    @Transactional
    public void inventoryOutEmpty(List<UseInventoryInoutDetailForm> list, StorageInventoryInout.BusinessType businessType, String deviceCode, StorageInventoryInout.BusinessDetailType businessDetailType,UseInventoryInout.BusinessType useBusinessType) {
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm:list){
            List<StorageInventorySpace> storageInventorySpaces=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));
            if (storageInventorySpaces.get(0).getQuantity()>0){
                throw new BusinessException("有库存不能清空");
            }
            inventorySpaceService.removeById(storageInventorySpaces.get(0).getId());
            //查询cab_storage_single_inventory_product暂存柜产品库存(单个柜子)是否还有库存，没有库存清空
            List<StorageSingleInventoryProduct> storageSingleInventoryProductList = storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("sku_code",storageInventorySpaces.get(0).getSkuCode()));
            Integer quantity = storageSingleInventoryProductList.stream().mapToInt(StorageSingleInventoryProduct::getQuantity).sum();
            if(quantity <= 0 ) {
                for (StorageSingleInventoryProduct storageSingleInventoryProduct : storageSingleInventoryProductList){
                    storageSingleInventoryProductService.removeById(storageSingleInventoryProduct.getId());
                 }
            }
        }
    }

    private List<StoresRequisitionProductForm> getRequestProduct(List<CellInventoryInoutDetailForm> list){
        List<StoresRequisitionProductForm> resultList=new ArrayList<>();
        Map<String,StoresRequisitionProductForm> resultMap=new HashMap<>();
        for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            StoresRequisitionProductForm temp=resultMap.get(cellInventoryInoutDetailForm.getSkuCode());
            if (temp==null){
                StoresRequisitionProductForm storesRequisitionProductForm=new StoresRequisitionProductForm();
                storesRequisitionProductForm.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                storesRequisitionProductForm.setNeckQuantity(cellInventoryInoutDetailForm.getQuantity());
                storesRequisitionProductForm.setId(cellInventoryInoutDetailForm.getRequestProductId());
                resultMap.put(cellInventoryInoutDetailForm.getSkuCode(),storesRequisitionProductForm);
            }else{
                temp.setNeckQuantity(temp.getNeckQuantity()+cellInventoryInoutDetailForm.getQuantity());
                resultMap.put(cellInventoryInoutDetailForm.getSkuCode(),temp);
            }
        }
        resultMap.keySet().forEach(item->{
            resultList.add(resultMap.get(item));
        });
        return resultList;
    }

    CellInventoryInout saveCellInventoryInOut(String deviceCode, CellInventoryInout.BusinessType businessType,List<UseInventoryInoutDetailForm> list,Long storageInventoryInoutId){
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String enterpriseName=JwtUtils.getEnterpriseName();
        String roleName=JwtUtils.getRoleName();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        String channelCode=JwtUtils.getChannelCode();
        Long roleId=JwtUtils.getRoleId();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        String code=dynamicService.getDayNextCode("cab_cell_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        cellInventoryInout.setCode("OU-"+day+"-"+code);
        cellInventoryInout.setDay(Integer.valueOf(day));

        cellInventoryInout.setNo(Integer.valueOf(code));
        cellInventoryInout.setCreator(JwtUtils.getLoginUserId());
        cellInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        cellInventoryInout.setType(CellInventoryInout.Type.outByCabSpace);
        cellInventoryInout.setDeviceCode(deviceCode);
        cellInventoryInout.setCompanyId(enterpriseId);
        cellInventoryInout.setBusinessType(businessType);
        cellInventoryInout.setRemark(businessType.getDesc());
        cellInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        cellInventoryInout.setProcessId(list.get(0).getProcessId());
        cellInventoryInout.setDepartmentId(departmentId);
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInout.setRoleName(roleName);
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        cellInventoryInout.setTotal(getTotal(list));
        cellInventoryInout.setStorageInventoryInoutId(storageInventoryInoutId);
        cellInventoryInout.setChannelCode(channelCode);
        cellInventoryInout.setRoleId(roleId);
        CellInventoryOutSeq cellInventoryOutSeq=new CellInventoryOutSeq();
        cellInventoryOutSeqService.insert(cellInventoryOutSeq);
        Long id=cellInventoryOutSeqService.getId();
        String orderCode= StringUtils.leftPad(id.toString(),10,"0");
        cellInventoryInout.setOrderCode(orderCode);

        cellInventoryInoutDao.insert(cellInventoryInout);
         List<Cabinet> cabinets=cabinetService.list(new QueryWrapper<Cabinet>().eq("code",list.get(0).getCabCode()));
         for (UseInventoryInoutDetailForm cellInventoryInoutDetailForm:list) {
             CellInventoryInoutDetail cellInventoryInoutDetail = new CellInventoryInoutDetail();
             BeanUtils.copyProperties(cellInventoryInoutDetailForm, cellInventoryInoutDetail);
             cellInventoryInoutDetail.setId(null);
             cellInventoryInoutDetail.setCreator(creator);
             cellInventoryInoutDetail.setCreatorName(creatorName);
             cellInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
             cellInventoryInoutDetail.setCompanyId(enterpriseId);
             cellInventoryInoutDetail.setType(CellInventoryInoutDetail.Type.outByCabSpace);
             cellInventoryInoutDetail.setInoutId(cellInventoryInout.getId());
             cellInventoryInoutDetail.setChannelCode(channelCode);
             if (cellInventoryInoutDetail.getQuantity()>0){
                 cellInventoryInoutDetail.setQuantity(cellInventoryInoutDetail.getQuantity()*-1);
             }
             if (cabinets.size()>0){
                 cellInventoryInoutDetail.setMainCabCode(cabinets.get(0).getBelongCabinet());
             }
             cellInventoryInoutDetailDao.insert(cellInventoryInoutDetail);
         }
         return cellInventoryInout;
    }






    @Override
    @Transactional
    public StorageInventoryInout inventoryOut4Check(List<StorageInventoryInoutDetailForm> list, StorageInventoryInout.BusinessType businessType, Long checkedResultId, StorageInventoryInout.BusinessDetailType businessDetailType, StorageInventoryInout.BusinessTypeChecked businessTypeChecked, Long checkedInventoryInoutId) {
        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        String departmentName = JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        String channelCode=JwtUtils.getChannelCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        String code = dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("OUC-" + day + "-" + code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(JwtUtils.getLoginUserId());
        storageInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.out);
        storageInventoryInout.setBusinessType(businessType);
        storageInventoryInout.setBusinessTypeChecked(businessTypeChecked);
        storageInventoryInout.setCheckTime(LocalDateTime.now());
        storageInventoryInout.setCheckUserId(JwtUtils.getLoginUserId());
        storageInventoryInout.setCheckUserName(JwtUtils.getLoginUsername());
        storageInventoryInout.setStatus(StorageInventoryInout.Status.checked);
        storageInventoryInout.setIsCheck(true);
        storageInventoryInout.setCheckedResultId(checkedResultId);
        storageInventoryInout.setCompanyId(enterpriseId);
        storageInventoryInout.setBusinessDetailType(businessDetailType);
        storageInventoryInout.setRemark(businessDetailType.getDesc());
        storageInventoryInout.setCheckInventoryInoutId(checkedInventoryInoutId);
        storageInventoryInout.setEnterpriseCode(enterpriseCode);
        storageInventoryInout.setTotal(getTotal2(list,storageInventoryInout.getOperationType()));
        storageInventoryInout.setDepartmentName(departmentName);
        storageInventoryInout.setDepartmentId(JwtUtils.getDepartmentId());
        storageInventoryInout.setCostCenter(JwtUtils.getCostCenter());
        storageInventoryInout.setRoleName(roleName);
        storageInventoryInout.setRoleId(roleId);
        storageInventoryInout.setChannelCode(channelCode);
//        storageInventoryInout.setUseInventoryInoutId(usein)
//        storageInventoryInout.setBusinessTypeChecked(businessTypeChecked);
        inventoryInoutService.save(storageInventoryInout);
        List<UseInventoryInoutDetailForm> listOut = new ArrayList<>();
        for (StorageInventoryInoutDetailForm detailForm : list) {
            UseInventoryInoutDetailForm cellInventoryInoutDetailForm = new UseInventoryInoutDetailForm();
            BeanUtils.copyProperties(detailForm, cellInventoryInoutDetailForm);
            listOut.add(cellInventoryInoutDetailForm);
        }
        if (StorageInventoryInout.BusinessTypeChecked.temp.equals(businessTypeChecked)) {
//            useInventoryInoutDetailService.inventoryIn4TempCabInventoryOut(listOut,storageInventoryInout.getId(),UseInventoryInout.BusinessType.virtualOutByCheck,null,StorageInventoryInout.BusinessDetailType.virtualOutByCheck,UseInventoryInout.Type.inByCheck);
        }
        Long storageInventoryCheckId = saveDetail4CheckOut(listOut, storageInventoryInout.getId(), UseInventoryInout.Type.out.name(), businessType, true, checkedResultId, businessDetailType, checkedInventoryInoutId, businessTypeChecked);
        if (StorageInventoryInout.BusinessTypeChecked.temp.equals(businessTypeChecked)) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSettingTime(listOut.get(i).getSettingTime());
                list.get(i).setRemainingTime(listOut.get(i).getRemainingTime());
                list.get(i).setLifeUnit(listOut.get(i).getLifeUnit());
                list.get(i).setParentLabelCode(listOut.get(i).getParentLabelCode());
                list.get(i).setDeviceCode(listOut.get(0).getDeviceCode());
            }
        }
        storageInventoryInout.setStorageInventoryCheckId(storageInventoryCheckId);
        sendMsg(storageInventoryInout);
        return storageInventoryInout;
    }

    @Override
    public CabinetCargoSpaceVO getUsableSpaces(UseInventoryInoutDetailForm useInventoryInoutDetailForm, StorageInventoryInout.BusinessType businessType) {
        Long creator = JwtUtils.getLoginUserId();
        if (useInventoryInoutDetailForm.getQuantity() == null) {
            useInventoryInoutDetailForm.setQuantity(1);
        }

        Long principal = null;
        Long productTypeId = null;
        if (CabinetCargoSpace.SpaceNature.personal.equals(useInventoryInoutDetailForm.getStorageType())) {
            principal = JwtUtils.getLoginUserId();
        } else if (CabinetCargoSpace.SpaceNature.specialClass.equals(useInventoryInoutDetailForm.getStorageType())) {
            Map paramMap = new HashMap();
            paramMap.put("skuCode", useInventoryInoutDetailForm.getSkuCode());
            List<ProductDetailVO> productDetailVOS = productDetailService.list4app(paramMap);
            if (productDetailVOS.size() == 0) {
                throw new BusinessException("未找到产品SKU");
            }
            productTypeId = productDetailVOS.get(0).getProductTypeId();
        } else if (CabinetCargoSpace.SpaceNature.sku.equals(useInventoryInoutDetailForm.getStorageType())) {

        } else if (CabinetCargoSpace.SpaceNature.common.equals(useInventoryInoutDetailForm.getStorageType())) {

//        }else if(CabinetCargoSpace.SpaceNature.repair.equals(useInventoryInoutDetailForm.getStorageType())){
//
//        }else if(CabinetCargoSpace.SpaceNature.recycle.equals(useInventoryInoutDetailForm.getStorageType())){
//
        } else {
            throw new BusinessException("货位存贮性质参数错误");
        }

        if (StorageInventoryInout.BusinessType.recycle.equals(businessType) || StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
            if (productDetails.size() > 0) {
                productTypeId = productDetails.get(0).getProductTypeId();
                CabinetCargoSpace.SpaceNature spaceNature = null;
                if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
                    spaceNature = CabinetCargoSpace.SpaceNature.recycle;
                } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
                    spaceNature = CabinetCargoSpace.SpaceNature.repair;
                }
                List<CabinetCargoSpaceVO> spaceVOS = cargoSpaceService.getUsedSpace(useInventoryInoutDetailForm.getCabCode(), businessType.getValue(), useInventoryInoutDetailForm.getQuantity(), null, spaceNature.name(), spaceNature.getValue(), principal, productTypeId, creator);
                if (spaceVOS.size() > 0) {
                    return spaceVOS.get(0);
                }

                spaceVOS = cargoSpaceService.getUsedSpace(useInventoryInoutDetailForm.getCabCode(), businessType.getValue(), useInventoryInoutDetailForm.getQuantity(), null, CabinetCargoSpace.SpaceNature.specialClass.name(), CabinetCargoSpace.SpaceNature.specialClass.getValue(), principal, productTypeId, creator);
                if (spaceVOS.size() > 0) {
                    return spaceVOS.get(0);
                }
                List<CabinetCargoSpaceVO> emptySpaces = cargoSpaceService.getEmptySpaces(useInventoryInoutDetailForm.getCabCode(), spaceNature.name(), spaceNature.getValue(), principal, productTypeId);
                if (emptySpaces.size() > 0) {
                    return emptySpaces.get(0);
                }
                emptySpaces = cargoSpaceService.getEmptySpaces(useInventoryInoutDetailForm.getCabCode(), CabinetCargoSpace.SpaceNature.specialClass.name(), CabinetCargoSpace.SpaceNature.specialClass.getValue(), principal, productTypeId);
                if (emptySpaces.size() > 0) {
                    return emptySpaces.get(0);
                }
            }

            productTypeId = null;
            List<CabinetCargoSpaceVO> spaceVOS = cargoSpaceService.getUsedSpace(useInventoryInoutDetailForm.getCabCode(), businessType.getValue(), useInventoryInoutDetailForm.getQuantity(), useInventoryInoutDetailForm.getSkuCode(), useInventoryInoutDetailForm.getStorageType().name(), useInventoryInoutDetailForm.getStorageType().getValue(), principal, productTypeId, creator);
            if (spaceVOS.size() > 0) {
                return spaceVOS.get(0);
            }


        }
        List<CabinetCargoSpaceVO> emptySpaces = cargoSpaceService.getEmptySpaces(useInventoryInoutDetailForm.getCabCode(), useInventoryInoutDetailForm.getStorageType().name(), useInventoryInoutDetailForm.getStorageType().getValue(), principal, productTypeId);
        if (emptySpaces.size() > 0) {
            return emptySpaces.get(0);
        }
        return null;
    }

    @Override
    public CabinetCargoSpaceVO getUsableSpaces(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, String skuCode, StorageInventoryInout.BusinessType businessType) {
        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<CabinetCargoSpaceVO> spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), creator, null, skuCode, null, 1, businessType.getValue());
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), creator, null, skuCode);
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
//        spaceVOS=cargoSpaceService.getUsedSpace(cabCodes,spaceType.getValue(),creator,null,null,skuCode,1,businessType.getValue());
//        if (spaceVOS.size()>0){
//            return spaceVOS.get(0);
//        }
        List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCode));
        if (productDetails.size() > 0) {
            Long productTypeId = productDetails.get(0).getProductTypeId();
            if (productTypeId != null) {
                spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), creator, productTypeId, null, null, 1, businessType.getValue());
                if (spaceVOS.size() > 0) {
                    return spaceVOS.get(0);
                }
                spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), creator, productTypeId, null);
                if (spaceVOS.size() > 0) {
                    return spaceVOS.get(0);
                }
            }
        }
        spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), creator, null, null, null, 1, businessType.getValue());
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), creator, null, null);
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }

        spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), null, null, null, null, 1, businessType.getValue());
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), null, null, null);
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }


        spaceType = CabinetCargoSpace.SpaceType.common;
        spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), creator, null, skuCode, null, 1, businessType.getValue());
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), creator, null, skuCode);
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), creator, null, null, skuCode, 1, businessType.getValue());
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }

        if (productDetails.size() > 0) {
            Long productTypeId = productDetails.get(0).getProductTypeId();
            if (productTypeId != null) {
                spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), creator, productTypeId, null, null, 1, businessType.getValue());
                if (spaceVOS.size() > 0) {
                    return spaceVOS.get(0);
                }
                spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), creator, productTypeId, null);
                if (spaceVOS.size() > 0) {
                    return spaceVOS.get(0);
                }
            }
        }
        spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), creator, null, null, null, 1, businessType.getValue());
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), creator, null, null);
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getUsedSpace(cabCodes, spaceType.getValue(), null, null, null, null, 1, businessType.getValue());
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }
        spaceVOS = cargoSpaceService.getEmptySpaces(cabCodes, spaceType.getValue(), null, null, null);
        if (spaceVOS.size() > 0) {
            return spaceVOS.get(0);
        }

        return null;
    }

    public CabinetCargoSpaceVO getSpaces(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, String skuCode, StorageInventoryInout.BusinessType businessType) {

        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
//        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag = true;
        }

        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCode));

        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = cargoSpaceService.getSpaceByCabCode(cabCodes);
        Map<String, List<CabinetCargoSpaceVO>> resultMap = new HashMap<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory() >= cabinetCargoSpaceVO.getQuantity()) {
                continue;
            }
//            String quantityKey="";
//            if (cabinetCargoSpaceVO.getQuantityInventory()>0){
//                quantityKey="quantity>0";
//            }

            //product type is not null & sku code is null
            if (cabinetCargoSpaceVO.getSpaceProductType() != 0 && StringUtils.isBlank(cabinetCargoSpaceVO.getSkuCode())) {

                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + principal +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key2, tempList);
                        }
                        // user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }


                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                    }

                }else{
                    //user share N sku share N
                    String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                            "user:" + "" +
                            "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                            + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                            + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key2, tempList);
                    }
                    // user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }


                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" +"" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                }




               //product type is null
            } else {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key, tempList);
                        }

                        //user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" +principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" +"" +
                            "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                            "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                            "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key, tempList);
                    }

                    //user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                }


            }

        }
        if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            if (CabinetCargoSpace.SpaceNature.common.equals(spaceNature)) {
                CabinetCargoSpaceVO cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.temp, creator, skuCode, businessType, spaceNature);
                if (cabinetCargoSpaceVO == null) {
                    cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
                }
                return cabinetCargoSpaceVO;
            } else if (CabinetCargoSpace.SpaceNature.personal.equals(spaceNature)) {
                CabinetCargoSpaceVO cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.temp, creator, skuCode, businessType, spaceNature);
                if (cabinetCargoSpaceVO == null) {
                    cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
                }
//                if (cabinetCargoSpaceVO==null){
//                    cabinetCargoSpaceVO=this.getUserSpecialSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
//                }
//                if (cabinetCargoSpaceVO==null){
//                    cabinetCargoSpaceVO=this.getUserCommonSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
//                }
                return cabinetCargoSpaceVO;
            } else {
                throw new BusinessException("专人 公共存贮參數错误");
            }
        }
        {
            CabinetCargoSpaceVO cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, spaceType, creator, skuCode, businessType, spaceNature);
            if (cabinetCargoSpaceVO == null) {
                cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
            }
            if (cabinetCargoSpaceVO == null) {
                cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, spaceType, creator, skuCode, businessType, spaceNature);
            }
            if (cabinetCargoSpaceVO == null) {
                cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
            }
            return cabinetCargoSpaceVO;
        }
    }

    private List<String> getNoRepeateSkuCodes(List<String> skuCodes){
        List<String> skuCodeList=new ArrayList<>();
        Map<String,String> skuCodeMap=new HashMap<>();
        skuCodes.forEach(e->{
            if(!skuCodeMap.containsKey(e)){
                skuCodeList.add(e);
                skuCodeMap.put(e,e);
            }
        });
        return skuCodeList;
    }

    public CabinetCargoSpaceVO getSpaces(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, List<String> skuCodes, StorageInventoryInout.BusinessType businessType,Integer quantity) {
        skuCodes=getNoRepeateSkuCodes(skuCodes);
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag = true;
        }

        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
            if (skuCodes.size()>1&&!spaceTempSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放且不允许多存");
            }
            if (!spaceTempMoreFlag&&quantity>1){
                throw new BusinessException("已设置暂存不允许存多个");
            }
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<ProductDetail> productDetails = new ArrayList<>();
        if (skuCodes.size()==1||productDetailService.countProductTypes(skuCodes)==1){
            productDetails=productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCodes.get(0)));
        }

        String skuCode="";
        if (skuCodes.size()==1){
            skuCode=skuCodes.get(0);
        }else{
            for (String skuCodeTemp:skuCodes){
                skuCode=skuCodeTemp+",";
            }
        }

        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = cargoSpaceService.getSpaceByCabCode(cabCodes);
        Map<String, List<CabinetCargoSpaceVO>> resultMap = new HashMap<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory() >= cabinetCargoSpaceVO.getQuantity()||
                    ((cabinetCargoSpaceVO.getQuantityInventory()+quantity)>cabinetCargoSpaceVO.getQuantity())) {
                continue;
            }
            if (StorageInventorySpace.BusinessType.exhibit.equals(cabinetCargoSpaceVO.getBusinessType())){
                continue;
            }
//            String quantityKey="";
//            if (cabinetCargoSpaceVO.getQuantityInventory()>0){
//                quantityKey="quantity>0";
//            }


            if (cabinetCargoSpaceVO.getSpaceProductType() != 0 && StringUtils.isBlank(cabinetCargoSpaceVO.getSkuCode())) {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String [] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + principal +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key2, tempList);
                        }
                        // user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }


                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                            "user:" + "" +
                            "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                            + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                            + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key2, tempList);
                    }
                    // user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }


                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                }


            } else {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key, tempList);
                        }

                        //user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                            "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                            "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                            "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key, tempList);
                    }

                    //user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                }


            }

        }
        if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            if (CabinetCargoSpace.SpaceNature.common.equals(spaceNature)) {
                CabinetCargoSpaceVO cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.temp, creator, skuCode, businessType, spaceNature);
                if (cabinetCargoSpaceVO == null) {
                    cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
                }
                return cabinetCargoSpaceVO;
            } else if (CabinetCargoSpace.SpaceNature.personal.equals(spaceNature)) {
                CabinetCargoSpaceVO cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.temp, creator, skuCode, businessType, spaceNature);
                if (cabinetCargoSpaceVO == null) {
                    cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
                }
//                if (cabinetCargoSpaceVO==null){
//                    cabinetCargoSpaceVO=this.getUserSpecialSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
//                }
//                if (cabinetCargoSpaceVO==null){
//                    cabinetCargoSpaceVO=this.getUserCommonSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
//                }
                return cabinetCargoSpaceVO;
            } else {
                throw new BusinessException("专人 公共存贮參數错误");
            }
        }
        {
            CabinetCargoSpaceVO cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, spaceType, creator, skuCode, businessType, spaceNature);
            if (cabinetCargoSpaceVO == null) {
                cabinetCargoSpaceVO = this.getUserSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
            }
            if (cabinetCargoSpaceVO == null) {
                cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, spaceType, creator, skuCode, businessType, spaceNature);
            }
            if (cabinetCargoSpaceVO == null) {
                cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
            }
            return cabinetCargoSpaceVO;
        }
    }

    @Override
    public CabSpaceResultVO getUserSpaces(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, String skuCode, StorageInventoryInout.BusinessType businessType, List<Integer> spaceTypes) {
        CabSpaceResultVO cabSpaceResultVO=new CabSpaceResultVO();
        cabSpaceResultVO.setIsHasUserSpace(false);
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
//        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag = true;
        }

        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCode));
        Long userId = JwtUtils.getLoginUserId();
        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = new ArrayList<>();
        List<CabinetCargoSpaceVO> cabinetCargoSpaceList = cargoSpaceService.getUserSpaceByCabCode(cabCodes, spaceTypes, userId);
        cabinetCargoSpaceList.forEach(e->{
            if ((","+e.getPrincipal()+",").contains(","+userId+",")){
                cabinetCargoSpaceVOS.add(e);
                cabSpaceResultVO.setIsHasUserSpace(true);
            }
        });
        List<CabinetCargoSpaceVO> resultList = new ArrayList<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory() >= cabinetCargoSpaceVO.getQuantity()) {
                continue;
            }
            if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCode()) && !skuCode.equals(cabinetCargoSpaceVO.getSkuCode())) {
                continue;
            }
            if (StorageInventorySpace.BusinessType.recycle.equals(cabinetCargoSpaceVO.getBusinessType())||
                    StorageInventorySpace.BusinessType.repair.equals(cabinetCargoSpaceVO.getBusinessType())||
                    StorageInventorySpace.BusinessType.exhibit.equals(cabinetCargoSpaceVO.getBusinessType())) {
                continue;
            }
            if (cabinetCargoSpaceVO.getSpaceProductType() != null && cabinetCargoSpaceVO.getSpaceProductType() != 0 &&
                    productDetails.size() > 0 && productDetails.get(0).getProductTypeId() != null && productDetails.get(0).getProductTypeId() != 0 &&
                    !cabinetCargoSpaceVO.getSpaceProductType().equals(productDetails.get(0).getProductTypeId())
            ) {
                continue;

            }
            if (!spaceTempSkuShareFlag && StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())
                    && !skuCode.equals(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                continue;
            }
            resultList.add(cabinetCargoSpaceVO);
        }
        cabSpaceResultVO.setList(resultList);
        return cabSpaceResultVO;
    }

    @Override
    public CabSpaceResultVO getUserSpaces(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, List<String> skuCodes, StorageInventoryInout.BusinessType businessType, List<Integer> spaceTypes,Integer quantity) {
        CabSpaceResultVO cabSpaceResultVO=new CabSpaceResultVO();
        cabSpaceResultVO.setIsHasUserSpace(false);
        skuCodes=getNoRepeateSkuCodes(skuCodes);
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
//        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag = true;
        }

        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
            if (skuCodes.size()>1&&!spaceTempSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放且不允许多存");
            }
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<ProductDetail> productDetails = new ArrayList<>();
        if (skuCodes.size()==1||productDetailService.countProductTypes(skuCodes)==1){
            productDetails=productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCodes.get(0)));
        }
        String skuCode="";
        if (skuCodes.size()==1){
            skuCode=skuCodes.get(0);
        }else{
            for (String skuCodeTemp:skuCodes){
                skuCode=skuCodeTemp+",";
            }
        }
        Long userId = JwtUtils.getLoginUserId();
        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = new ArrayList<>();
        List<CabinetCargoSpaceVO> cabinetCargoSpaceList = cargoSpaceService.getUserSpaceByCabCode(cabCodes, spaceTypes, userId);
        cabinetCargoSpaceList.forEach(e->{
            if ((","+e.getPrincipal()+",").contains(","+userId+",")){
                cabinetCargoSpaceVOS.add(e);
                cabSpaceResultVO.setIsHasUserSpace(true);
            }
        });
        if(cabinetCargoSpaceVOS.size() == 0){
            throw new BusinessException("您没有专属存储权限，请选择其他存储方式，或者联系管理员开通。");
        }
        List<CabinetCargoSpaceVO> resultList = new ArrayList<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory() >= cabinetCargoSpaceVO.getQuantity()||
                    ((cabinetCargoSpaceVO.getQuantityInventory()+quantity)>cabinetCargoSpaceVO.getQuantity())) {
                continue;
            }
            if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCode()) && !skuCode.equals(cabinetCargoSpaceVO.getSkuCode())) {
                continue;
            }
            if (StorageInventorySpace.BusinessType.recycle.equals(cabinetCargoSpaceVO.getBusinessType())||
                    StorageInventorySpace.BusinessType.repair.equals(cabinetCargoSpaceVO.getBusinessType())||
                    StorageInventorySpace.BusinessType.exhibit.equals(cabinetCargoSpaceVO.getBusinessType())) {
                continue;
            }
            if (cabinetCargoSpaceVO.getSpaceProductType() != null && cabinetCargoSpaceVO.getSpaceProductType() != 0 &&
                    productDetails.size() > 0 && productDetails.get(0).getProductTypeId() != null && productDetails.get(0).getProductTypeId() != 0 &&
                    !cabinetCargoSpaceVO.getSpaceProductType().equals(productDetails.get(0).getProductTypeId())
            ) {
                continue;

            }
            if (!spaceTempSkuShareFlag && StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())
                    && !skuCode.equals(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                continue;
            }
            resultList.add(cabinetCargoSpaceVO);
        }
        cabSpaceResultVO.setList(resultList);
        return cabSpaceResultVO;
    }

    public CabinetCargoSpaceVO getSpaces4OldNew(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, String skuCode, StorageInventoryInout.BusinessType businessType,Integer quantity) {

        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag = true;
        }

        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCode));

        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = cargoSpaceService.getSpaceByCabCode(cabCodes);
        Map<String, List<CabinetCargoSpaceVO>> resultMap = new HashMap<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory()+quantity > cabinetCargoSpaceVO.getQuantity()) {
                continue;
            }
            if (StorageInventorySpace.BusinessType.exhibit.equals(cabinetCargoSpaceVO.getBusinessType())){
                continue;
//            String quantityKey=""
            };
//            if (cabinetCargoSpaceVO.getQuantityInventory()>0){
//                quantityKey="quantity>0";
//            }


            if (cabinetCargoSpaceVO.getSpaceProductType() != 0 && StringUtils.isBlank(cabinetCargoSpaceVO.getSkuCode())) {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + principal +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key2, tempList);
                        }
                        // user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }


                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                            "user:" + "" +
                            "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                            + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                            + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key2, tempList);
                    }
                    // user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }


                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                }


            } else {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key, tempList);
                        }

                        //user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                            "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                            "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                            "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key, tempList);
                    }

                    //user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                }


            }

        }
        CabinetCargoSpaceVO cabinetCargoSpaceVO = null;
//            CabinetCargoSpaceVO cabinetCargoSpaceVO=this.getUserSpaces(systemRuleInfo,resultMap,productDetails,spaceType,creator,skuCode,businessType,spaceNature);
//            if (cabinetCargoSpaceVO==null){
//                cabinetCargoSpaceVO=this.getUserSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
//            }
        if (cabinetCargoSpaceVO == null) {
            cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, spaceType, creator, skuCode, businessType, spaceNature);
        }
        if (cabinetCargoSpaceVO == null) {
            cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
        }
        return cabinetCargoSpaceVO;

    }

    public CabinetCargoSpaceVO getSpaces4OldNewMoreKnife(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, List<String> skuCodes, StorageInventoryInout.BusinessType businessType,Integer quantity) {
        skuCodes=getNoRepeateSkuCodes(skuCodes);
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag = true;
        }

        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
            if (skuCodes.size()>1&&!spaceTempSkuShareFlag&&!spaceTempMoreFlag){
                throw new BusinessException("已设置不同的物料分开存放且不允许多存");
            }
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<ProductDetail> productDetails = new ArrayList<>();
        if (skuCodes.size()==1||productDetailService.countProductTypes(skuCodes)==1){
            productDetails=productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCodes.get(0)));
        }

        String skuCode="";
        if (skuCodes.size()==1){
            skuCode=skuCodes.get(0);
        }else{
            for (String skuCodeTemp:skuCodes){
                skuCode=skuCodeTemp+",";
            }
        }

        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = cargoSpaceService.getSpaceByCabCode(cabCodes);
        Map<String, List<CabinetCargoSpaceVO>> resultMap = new HashMap<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory() >= cabinetCargoSpaceVO.getQuantity()||
                    ((cabinetCargoSpaceVO.getQuantityInventory()+quantity)>cabinetCargoSpaceVO.getQuantity())) {
                continue;
            }
//            String quantityKey="";
//            if (cabinetCargoSpaceVO.getQuantityInventory()>0){
//                quantityKey="quantity>0";
//            }


            if (cabinetCargoSpaceVO.getSpaceProductType() != 0 && StringUtils.isBlank(cabinetCargoSpaceVO.getSkuCode())) {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + principal +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key2, tempList);
                        }
                        // user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }


                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                            "user:" + "" +
                            "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                            + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                            + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key2, tempList);
                    }
                    // user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }


                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                }


            } else {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArrayl=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArrayl){
                        //user share N sku share N
                        String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key, tempList);
                        }

                        //user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal+
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                            "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                            "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                            "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key, tempList);
                    }

                    //user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                }


            }

        }
        CabinetCargoSpaceVO cabinetCargoSpaceVO = null;
//            CabinetCargoSpaceVO cabinetCargoSpaceVO=this.getUserSpaces(systemRuleInfo,resultMap,productDetails,spaceType,creator,skuCode,businessType,spaceNature);
//            if (cabinetCargoSpaceVO==null){
//                cabinetCargoSpaceVO=this.getUserSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
//            }
        if (cabinetCargoSpaceVO == null) {
            cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, spaceType, creator, skuCode, businessType, spaceNature);
        }
        if (cabinetCargoSpaceVO == null) {
            cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
        }
        return cabinetCargoSpaceVO;

    }

    public CabinetCargoSpaceVO getSpaces4OldNew(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes,List<String> skuCodes, StorageInventoryInout.BusinessType businessType,Integer quantity) {
        skuCodes=getNoRepeateSkuCodes(skuCodes);
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag = true;
        }



        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
            if (skuCodes.size()>1&&!spaceSkuShareFlag){
                throw new BusinessException("已设置不同的物料分开存放");
            }
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
            if (skuCodes.size()>1&&!spaceTempSkuShareFlag&&!spaceTempMoreFlag){
                throw new BusinessException("已设置不同的物料分开存放且不允许多存");
            }
        } else {
            throw new BusinessException("库位性质参数异常");
        }

        List<ProductDetail> productDetails = new ArrayList<>();
        if (skuCodes.size()==1||productDetailService.countProductTypes(skuCodes)==1){
            productDetails=productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCodes.get(0)));
        }
        String skuCode="";
        if (skuCodes.size()==1){
            skuCode=skuCodes.get(0);
        }else{
            for (String skuCodeTemp:skuCodes){
                skuCode=skuCodeTemp+",";
            }
        }

        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = cargoSpaceService.getSpaceByCabCode(cabCodes);
        Map<String, List<CabinetCargoSpaceVO>> resultMap = new HashMap<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory() >= cabinetCargoSpaceVO.getQuantity()||
                    ((cabinetCargoSpaceVO.getQuantityInventory()+quantity)>cabinetCargoSpaceVO.getQuantity())) {
                continue;
            }
//            String quantityKey="";
//            if (cabinetCargoSpaceVO.getQuantityInventory()>0){
//                quantityKey="quantity>0";
//            }


            if (cabinetCargoSpaceVO.getSpaceProductType() != 0 && StringUtils.isBlank(cabinetCargoSpaceVO.getSkuCode())) {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + principal +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key2, tempList);
                        }
                        // user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }


                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" +principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                            "user:" + "" +
                            "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                            + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                            + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key2, tempList);
                    }
                    // user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }


                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                }


            } else {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArray){
                        //user share N sku share N
                        String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key, tempList);
                        }

                        //user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                            "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                            "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                            "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key, tempList);
                    }

                    //user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                }


            }

        }
        CabinetCargoSpaceVO cabinetCargoSpaceVO = null;
//            CabinetCargoSpaceVO cabinetCargoSpaceVO=this.getUserSpaces(systemRuleInfo,resultMap,productDetails,spaceType,creator,skuCode,businessType,spaceNature);
//            if (cabinetCargoSpaceVO==null){
//                cabinetCargoSpaceVO=this.getUserSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
//            }
        if (cabinetCargoSpaceVO == null) {
            cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, spaceType, creator, skuCode, businessType, spaceNature);
        }
        if (cabinetCargoSpaceVO == null) {
            cabinetCargoSpaceVO = this.getCommonSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
        }
        return cabinetCargoSpaceVO;

    }

    public CabinetCargoSpaceVO getSpacesOld(CabinetCargoSpace.SpaceNature spaceNature, String cabCodes, String skuCode, StorageInventoryInout.BusinessType businessType) {

        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
            spaceTempMoreFlag = true;
        }

        Long creator = JwtUtils.getLoginUserId();
        CabinetCargoSpace.SpaceType spaceType = null;
        if (StorageInventoryInout.BusinessType.recycle.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.recycle;
        } else if (StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.repair;
        } else if (StorageInventoryInout.BusinessType.temp.equals(businessType)) {
            spaceType = CabinetCargoSpace.SpaceType.temp;
        } else {
            throw new BusinessException("库位性质参数异常");
        }
        List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", skuCode));

        List<CabinetCargoSpaceVO> cabinetCargoSpaceVOS = cargoSpaceService.getSpaceByCabCode(cabCodes);
        Map<String, List<CabinetCargoSpaceVO>> resultMap = new HashMap<>();
        for (CabinetCargoSpaceVO cabinetCargoSpaceVO : cabinetCargoSpaceVOS) {
            if (cabinetCargoSpaceVO.getQuantityInventory() >= cabinetCargoSpaceVO.getQuantity()) {
                continue;
            }
//            String quantityKey="";
//            if (cabinetCargoSpaceVO.getQuantityInventory()>0){
//                quantityKey="quantity>0";
//            }


            if (cabinetCargoSpaceVO.getSpaceProductType() != 0 && StringUtils.isBlank(cabinetCargoSpaceVO.getSkuCode())) {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String []principalArrayl=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for (String principal:principalArrayl){
                        //user share N sku share N
                        String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + principal +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key2, tempList);
                        }
                        // user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }


                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                    "user:" + principal +
                                    "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                    + "storageUser:"
                                    + "skuCodeCurrent:";
                            if (!resultMap.containsKey(key2)) {
                                tempList = resultMap.get(key2);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key2, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                            "user:" + "" +
                            "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                            + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                            + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key2);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key2, tempList);
                    }
                    // user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "")
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }


                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key2 = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() +
                                "user:" + "" +
                                "productType:" + (cabinetCargoSpaceVO.getSpaceProductType() != 0 ? cabinetCargoSpaceVO.getSpaceProductType() : "") +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "")
                                + "storageUser:"
                                + "skuCodeCurrent:";
                        if (!resultMap.containsKey(key2)) {
                            tempList = resultMap.get(key2);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key2, tempList);
                            }
                        }

                    }
                }


            } else {
                if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getPrincipal())){
                    String[] principalArray=cabinetCargoSpaceVO.getPrincipal().split(",");
                    for(String principal:principalArray){
                        //user share N sku share N
                        String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                        if (tempList != null) {
                            tempList.add(cabinetCargoSpaceVO);
                        } else {
                            tempList = new ArrayList<>();
                            tempList.add(cabinetCargoSpaceVO);
                            resultMap.put(key, tempList);
                        }

                        //user share N sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share N
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                            if (resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                        //user share Y sku share Y
                        if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                            key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + principal +
                                    "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                    "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                    "storageUser:" +
                                    "skuCodeCurrent:";
                            if (!resultMap.containsKey(key)) {
                                tempList = resultMap.get(key);
                                if (tempList != null) {
                                    tempList.add(cabinetCargoSpaceVO);
                                } else {
                                    tempList = new ArrayList<>();
                                    tempList.add(cabinetCargoSpaceVO);
                                    resultMap.put(key, tempList);
                                }
                            }

                        }
                    }
                }else{
                    //user share N sku share N
                    String key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                            "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                            "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                            "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                            "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                    List<CabinetCargoSpaceVO> tempList = resultMap.get(key);
                    if (tempList != null) {
                        tempList.add(cabinetCargoSpaceVO);
                    } else {
                        tempList = new ArrayList<>();
                        tempList.add(cabinetCargoSpaceVO);
                        resultMap.put(key, tempList);
                    }

                    //user share N sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" + (cabinetCargoSpaceVO.getUserId() != 0 ? cabinetCargoSpaceVO.getUserId() : "") +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share N
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:" + cabinetCargoSpaceVO.getSkuCodeCurrent();
                        if (resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                    //user share Y sku share Y
                    if (StringUtils.isNotBlank(cabinetCargoSpaceVO.getSkuCodeCurrent())) {
                        key = "spaceType:" + cabinetCargoSpaceVO.getSpaceType().getValue() + "user:" + "" +
                                "skuCode:" + cabinetCargoSpaceVO.getSkuCode() +
                                "businessType:" + (cabinetCargoSpaceVO.getBusinessType() != null ? cabinetCargoSpaceVO.getBusinessType().getValue() : "") +
                                "storageUser:" +
                                "skuCodeCurrent:";
                        if (!resultMap.containsKey(key)) {
                            tempList = resultMap.get(key);
                            if (tempList != null) {
                                tempList.add(cabinetCargoSpaceVO);
                            } else {
                                tempList = new ArrayList<>();
                                tempList.add(cabinetCargoSpaceVO);
                                resultMap.put(key, tempList);
                            }
                        }

                    }
                }


            }

        }
        /**spaceType creator skuCode start*/
        //config spaceType &creator &sku
//        String quantityKey="quantity>0";
        //creator is not null skuCode is not null &businessType is not null& user share N sku share N
        //user&sku
        //1 spaceType creator skuCode is not null,
        // businessType creatorCurrent skuCodeCurrent is not null/not empty space
        if (CabinetCargoSpace.SpaceNature.personal.equals(spaceNature) ||
                CabinetCargoSpace.SpaceNature.common.equals(spaceNature) ||
                spaceNature == null) {


            String key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
            List<CabinetCargoSpaceVO> resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (StorageInventoryInout.BusinessType.temp.equals(businessType) && spaceTempMoreFlag) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            //2 creator is not null skuCode is not null &businessType is null& user share N sku share N& empty
            //spaceType creator skuCode  is not null,
            // businessType currentCreator currentSkuCode is null/empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + skuCode + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            /**spaceType creator skuCode end*/
            /**spaceType creator skuType start*/
            if (productDetails.size() > 0) {
                Long productTypeId = productDetails.get(0).getProductTypeId();
                if (productTypeId != null) {
                    //config sapceType & creator productType
                    //user&productType & sku share N user share N
                    //creator is not null productType is not null& businessType is not null & sku share N user share N
                    //3
//                key="spaceType:"+spaceType.getValue()+"user:"+creator+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+creator+"skuCodeCurrent:"+skuCode;
                    //spaceType creator skuType  is not null
                    // businessType creatorCurrent skuCodeCurrent is not null/not empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }

                    // productType & user is null & sku share Y user share N
                    //sku share space
                    //spaceType creator skuType businessType is not null,sku share Y/not empty space
                    //spaceType creator skuType  is not null
                    // businessType creatorCurrent  is not null,skuCodeCurrent is null/not empty space
                    if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    /**
                     //productType & user is null & user share Y  sku share N
                     //user share storage
                     if ((spaceUserShareFlag&&!StorageInventoryInout.BusinessType.temp.equals(businessType))||
                     (spaceTempUserShareFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType))){
                     key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+"skuCodeCurrent:"+skuCode;
                     resultList=resultMap.get(key);
                     if (resultList!=null&&resultList.size()>0){
                     //                          return resultList.get(0);
                     if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     if (spaceTempMoreFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                     //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                     //                            return cabinetCargoSpaceVO;
                     //                        }
                     //                    }
                     }
                     }
                     // productType & user is null &n user share Y sku share Y
                     if ((spaceUserShareFlag&&spaceSkuShareFlag&&!StorageInventoryInout.BusinessType.temp.equals(businessType))||
                     (spaceTempUserShareFlag&&spaceSkuShareFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType))){
                     key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+"skuCodeCurrent:";
                     resultList=resultMap.get(key);
                     if (resultList!=null&&resultList.size()>0){
                     //                          return resultList.get(0);
                     if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     if (spaceTempMoreFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                     //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                     //                            return cabinetCargoSpaceVO;
                     //                        }
                     //                    }
                     }
                     }*/

                    //4 creator &productType &businessType is null & empty
                    //spaceType creator skuType  is not null，
                    // businessType creatorCurrent skuCodeCurrent is null/empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + "storageUser:" + "skuCodeCurrent:";
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
                        return resultList.get(0);
//                    if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                        return resultList.get(0);
//                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                    //creator is null productType&empty
                    /**
                     key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+"storageUser:";
                     resultList=resultMap.get(key);
                     if (resultList!=null&&resultList.size()>0){
                     return resultList.get(0);
                     //                    if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     //                        return resultList.get(0);
                     //                    }
                     //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                     //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                     //                            return cabinetCargoSpaceVO;
                     //                        }
                     //                    }
                     }*/
                }
            }
            /**spaceType creator skuType end*/
            /**spaceType creator start*/
            //config spaceType &creator
            //creator
            //creator is not null skuCode is null
            //5
            //spaceType creator is not null,skuCode is null
            // ,businessType creatorCurrent skuCodeCurrent is not  null/not empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            //creator is not null &sku share Y user share N
            //spaceType creator is not null,skuCode is null,
            // businessType creatorCurrent is not null,skuCodeCurrent is null/not empty space
            if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//                for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                    if (cabinetCargoSpaceVO.getBusinessType()==null){
//                        return cabinetCargoSpaceVO;
//                    }
//                }
                }
            }
            //6 creator&businessType is null & empty
            //spaceType creator is not null,skuCode is null,
            // businessType currentSkuCode currentCreator is  null/ empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
        }
        /**spaceType creator end*/
//        config spaceType&skuCode sku share N
        //sku
        //creator is null skuCode is not null
        /**spaceType skuCode start*/
        //7
        //spaceType skuCode is not null,creator is null,
        // businessType creatorCurrent skuCodeCurrent is  not null/ not empty space
        if (CabinetCargoSpace.SpaceNature.common.equals(spaceNature) || spaceNature == null) {
            String key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
            List<CabinetCargoSpaceVO> resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            //user share Y
            //spaceType skuCode is not null,creator is null,businessType  skuCodeCurrent is not null/not empty space
            //spaceType skuCode is not null,creator is null,
            // businessType  skuCodeCurrent is  not null ,creatorCurrent is null/ not empty space
            if ((spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//                for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                    if (cabinetCargoSpaceVO.getBusinessType()==null){
//                        return cabinetCargoSpaceVO;
//                    }
//                }
                }
            }
            //8 empty
            //spaceType skuCode is not null,creator is null,businessType creatorCurrent skuCodeCurrent is  null/empty space
            //spaceType skuCode is not null,creator is null,
            // businessType  skuCodeCurrent creatorCurrent is null/  empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            /**spaceType skuCode end*/
            //
            //creator is nul productType is not null storage user is not null

            /**spaceType skuType start*/
            if (productDetails.size() > 0) {
                Long productTypeId = productDetails.get(0).getProductTypeId();
                if (productTypeId != null) {
                    //config spaceType &product Type
                    //9
                    // creator &productType & user share N sku share N
                    //spaceType skuType is not null,creator is null,
                    // businessType  skuCodeCurrent creatorCurrent is  not null / not empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                    //productType& sku share Y user share N
                    //spaceType skuType is not null,creator is null,
                    // businessType   creatorCurrent is  not null,skuCodeCurrent is null / not empty space
                    if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    //creator is null &productType &user share Y sku share N
                    //spaceType skuType is not null,creator is null,
                    // businessType   skuCodeCurrent is  not null, creatorCurrent is null / not empty space
                    if ((spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    //productType & creator is null& businessType& user share Y sku share Y
                    //spaceType skuType is not null,creator is null,
                    // businessType    is  not null, creatorCurrent skuCodeCurrent is null / not empty space
                    if ((spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempUserShareFlag && spaceSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:";
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    //10 creator&productType &empty
//                key="spaceType:"+spaceType.getValue()+"user:"+creator+"productType:"+productTypeId+"businessType:"+"storageUser:"+"skuCodeCurrent:";
//                resultList=resultMap.get(key);
//                if (resultList!=null&&resultList.size()>0){
//                    return resultList.get(0);
////                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
////                        return resultList.get(0);
////                    }
////                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
////                        if (cabinetCargoSpaceVO.getBusinessType()==null){
////                            return cabinetCargoSpaceVO;
////                        }
////                    }
//                }
                    //creator is null productType&empty
                    //spaceType skuType is not null,creator is null,
                    // businessType  creatorCurrent skuCodeCurrent is null /  empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + "storageUser:" + "skuCodeCurrent:";
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
                        return resultList.get(0);
//                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                        return resultList.get(0);
//                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                }
            }
            /**spaceType skuType end*/

            /**spaceType start*/
            //config
            //creator is null productType is null skuCode is null
            //11 user share N sku share Y
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType  creatorCurrent  is not null,skuCodeCurrent is null / not  empty space
            if ((!spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (!spaceTempUserShareFlag && spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }
            }
            // user share Y sku share Y
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType    is not null,skuCodeCurrent creatorCurrent is null / not  empty space
            if ((spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempUserShareFlag && spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                  return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        return resultList.get(0);
                    }

//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }
            }

            //user share Y sku share N
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType   skuCodeCurrent is not null, creatorCurrent is null / not  empty space
            if ((spaceUserShareFlag && !spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempUserShareFlag && !spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }
            }
            // user share N sku share N
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType   creatorCurrent skuCodeCurrent is not null/ not  empty space
            if ((!spaceUserShareFlag && !spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (!spaceTempUserShareFlag && !spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        return resultList.get(0);
                    }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }

            }
//        config spaceType
            //12
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType   creatorCurrent skuCodeCurrent is  null/   empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
        }
        /**spaceType end*/
        return getSpaces(systemRuleInfo, resultMap, productDetails, CabinetCargoSpace.SpaceType.common, creator, skuCode, businessType, spaceNature);
    }

    CabinetCargoSpaceVO getUserSpaces(SystemRuleInfo systemRuleInfo, Map<String, List<CabinetCargoSpaceVO>> resultMap, List<ProductDetail> productDetails, CabinetCargoSpace.SpaceType spaceType, Long creator, String skuCode, StorageInventoryInout.BusinessType businessType, CabinetCargoSpace.SpaceNature spaceNature) {
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
            spaceTempMoreFlag = true;
        }


        /**spaceType creator skuCode start*/
        //config spaceType &creator &sku
//        String quantityKey="quantity>0";
        //creator is not null skuCode is not null &businessType is not null& user share N sku share N
        //user&sku
        //1 spaceType creator skuCode is not null,
        // businessType creatorCurrent skuCodeCurrent is not null/not empty space
//        if (CabinetCargoSpace.SpaceNature.personal.equals(spaceNature)||
//                CabinetCargoSpace.SpaceNature.common.equals(spaceNature)||
//                spaceNature==null) {


        String key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
        List<CabinetCargoSpaceVO> resultList = resultMap.get(key);
        if (resultList != null && resultList.size() > 0) {
            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                return resultList.get(0);
            }
            if (StorageInventoryInout.BusinessType.temp.equals(businessType) && spaceTempMoreFlag) {
                return resultList.get(0);
            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
        }
        //2 creator is not null skuCode is not null &businessType is null& user share N sku share N& empty
        //spaceType creator skuCode  is not null,
        // businessType currentCreator currentSkuCode is null/empty space
        key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + skuCode + "businessType:" + "storageUser:" + "skuCodeCurrent:";
        resultList = resultMap.get(key);
        if (resultList != null && resultList.size() > 0) {
            return resultList.get(0);
//            if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
        }
        /**spaceType creator skuCode end*/
        /**spaceType creator skuType start*/
        if (productDetails.size() > 0) {
            Long productTypeId = productDetails.get(0).getProductTypeId();
            if (productTypeId != null) {
                //config sapceType & creator productType
                //user&productType & sku share N user share N
                //creator is not null productType is not null& businessType is not null & sku share N user share N
                //3
//                key="spaceType:"+spaceType.getValue()+"user:"+creator+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+creator+"skuCodeCurrent:"+skuCode;
                //spaceType creator skuType  is not null
                // businessType creatorCurrent skuCodeCurrent is not null/not empty space
                key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        return resultList.get(0);
                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                }

                // productType & user is null & sku share Y user share N
                //sku share space
                //spaceType creator skuType businessType is not null,sku share Y/not empty space
                //spaceType creator skuType  is not null
                // businessType creatorCurrent  is not null,skuCodeCurrent is null/not empty space
                if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                        (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                }
                /**
                 //productType & user is null & user share Y  sku share N
                 //user share storage
                 if ((spaceUserShareFlag&&!StorageInventoryInout.BusinessType.temp.equals(businessType))||
                 (spaceTempUserShareFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType))){
                 key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+"skuCodeCurrent:"+skuCode;
                 resultList=resultMap.get(key);
                 if (resultList!=null&&resultList.size()>0){
                 //                          return resultList.get(0);
                 if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                 return resultList.get(0);
                 }
                 if (spaceTempMoreFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType)){
                 return resultList.get(0);
                 }
                 //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                 //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                 //                            return cabinetCargoSpaceVO;
                 //                        }
                 //                    }
                 }
                 }
                 // productType & user is null &n user share Y sku share Y
                 if ((spaceUserShareFlag&&spaceSkuShareFlag&&!StorageInventoryInout.BusinessType.temp.equals(businessType))||
                 (spaceTempUserShareFlag&&spaceSkuShareFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType))){
                 key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+"skuCodeCurrent:";
                 resultList=resultMap.get(key);
                 if (resultList!=null&&resultList.size()>0){
                 //                          return resultList.get(0);
                 if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                 return resultList.get(0);
                 }
                 if (spaceTempMoreFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType)){
                 return resultList.get(0);
                 }
                 //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                 //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                 //                            return cabinetCargoSpaceVO;
                 //                        }
                 //                    }
                 }
                 }*/

                //4 creator &productType &businessType is null & empty
                //spaceType creator skuType  is not null，
                // businessType creatorCurrent skuCodeCurrent is null/empty space
                key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + "storageUser:" + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
                    return resultList.get(0);
//                    if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                        return resultList.get(0);
//                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                }
                //creator is null productType&empty
                /**
                 key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+"storageUser:";
                 resultList=resultMap.get(key);
                 if (resultList!=null&&resultList.size()>0){
                 return resultList.get(0);
                 //                    if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                 //                        return resultList.get(0);
                 //                    }
                 //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                 //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                 //                            return cabinetCargoSpaceVO;
                 //                        }
                 //                    }
                 }*/
            }
        }
        /**spaceType creator skuType end*/
        /**spaceType creator start*/
        //config spaceType &creator
        //creator
        //creator is not null skuCode is null
        //5
        //spaceType creator is not null,skuCode is null
        // ,businessType creatorCurrent skuCodeCurrent is not  null/not empty space
        key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
        resultList = resultMap.get(key);
        if (resultList != null && resultList.size() > 0) {
            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                return resultList.get(0);
            }
            if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                return resultList.get(0);
            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
        }
        //creator is not null &sku share Y user share N
        //spaceType creator is not null,skuCode is null,
        // businessType creatorCurrent is not null,skuCodeCurrent is null/not empty space
        if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
            key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
//                for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                    if (cabinetCargoSpaceVO.getBusinessType()==null){
//                        return cabinetCargoSpaceVO;
//                    }
//                }
            }
        }
        //6 creator&businessType is null & empty
        //spaceType creator is not null,skuCode is null,
        // businessType currentSkuCode currentCreator is  null/ empty space
        key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + "storageUser:" + "skuCodeCurrent:";
        resultList = resultMap.get(key);
        if (resultList != null && resultList.size() > 0) {
            return resultList.get(0);
//            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
        }
//        }
        /**spaceType creator end*/

        return null;
    }

    CabinetCargoSpaceVO getCommonSpaces(SystemRuleInfo systemRuleInfo, Map<String, List<CabinetCargoSpaceVO>> resultMap, List<ProductDetail> productDetails, CabinetCargoSpace.SpaceType spaceType, Long creator, String skuCode, StorageInventoryInout.BusinessType businessType, CabinetCargoSpace.SpaceNature spaceNature) {
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag=true;
        }


//        config spaceType&skuCode sku share N
        //sku
        //creator is null skuCode is not null
        /**spaceType skuCode start*/
        //7
        //spaceType skuCode is not null,creator is null,
        // businessType creatorCurrent skuCodeCurrent is  not null/ not empty space
//        if (CabinetCargoSpace.SpaceNature.common.equals(spaceNature)||spaceNature==null) {
        String key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
        List<CabinetCargoSpaceVO> resultList = resultMap.get(key);
        if (resultList != null && resultList.size() > 0) {
            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                return resultList.get(0);
            }
            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                return resultList.get(0);
            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
        }
        //user share Y
        //spaceType skuCode is not null,creator is null,businessType  skuCodeCurrent is not null/not empty space
        //spaceType skuCode is not null,creator is null,
        // businessType  skuCodeCurrent is  not null ,creatorCurrent is null/ not empty space
        if ((spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                (spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
//                for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                    if (cabinetCargoSpaceVO.getBusinessType()==null){
//                        return cabinetCargoSpaceVO;
//                    }
//                }
            }
        }
        //8 empty
        //spaceType skuCode is not null,creator is null,businessType creatorCurrent skuCodeCurrent is  null/empty space
        //spaceType skuCode is not null,creator is null,
        // businessType  skuCodeCurrent creatorCurrent is null/  empty space
        key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + "storageUser:" + "skuCodeCurrent:";
        resultList = resultMap.get(key);
        if (resultList != null && resultList.size() > 0) {
            return resultList.get(0);
//            if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
        }
        /**spaceType skuCode end*/
        //
        //creator is nul productType is not null storage user is not null

        /**spaceType skuType start*/
        if (productDetails.size() > 0) {
            Long productTypeId = productDetails.get(0).getProductTypeId();
            if (productTypeId != null) {
                //config spaceType &product Type
                //9
                // creator &productType & user share N sku share N
                //spaceType skuType is not null,creator is null,
                // businessType  skuCodeCurrent creatorCurrent is  not null / not empty space
                key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                }
                //productType& sku share Y user share N
                //spaceType skuType is not null,creator is null,
                // businessType   creatorCurrent is  not null,skuCodeCurrent is null / not empty space
                if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                        (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                }
                //creator is null &productType &user share Y sku share N
                //spaceType skuType is not null,creator is null,
                // businessType   skuCodeCurrent is  not null, creatorCurrent is null / not empty space
                if ((spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                        (spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                }
                //productType & creator is null& businessType& user share Y sku share Y
                //spaceType skuType is not null,creator is null,
                // businessType    is  not null, creatorCurrent skuCodeCurrent is null / not empty space
                if ((spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                        (spaceTempUserShareFlag && spaceSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:";
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                }
                //10 creator&productType &empty
//                key="spaceType:"+spaceType.getValue()+"user:"+creator+"productType:"+productTypeId+"businessType:"+"storageUser:"+"skuCodeCurrent:";
//                resultList=resultMap.get(key);
//                if (resultList!=null&&resultList.size()>0){
//                    return resultList.get(0);
////                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
////                        return resultList.get(0);
////                    }
////                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
////                        if (cabinetCargoSpaceVO.getBusinessType()==null){
////                            return cabinetCargoSpaceVO;
////                        }
////                    }
//                }
                //creator is null productType&empty
                //spaceType skuType is not null,creator is null,
                // businessType  creatorCurrent skuCodeCurrent is null /  empty space
                key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + "storageUser:" + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
                    return resultList.get(0);
//                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                        return resultList.get(0);
//                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                }
            }
        }
        /**spaceType skuType end*/

        /**spaceType start*/
        //config
        //creator is null productType is null skuCode is null
        //11 user share N sku share Y
        //spaceType  is not null,creator skuType skuCode is null,
        // businessType  creatorCurrent  is not null,skuCodeCurrent is null / not  empty space
        if ((!spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                (!spaceTempUserShareFlag && spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
        }
        // user share Y sku share Y
        //spaceType  is not null,creator skuType skuCode is null,
        // businessType    is not null,skuCodeCurrent creatorCurrent is null / not  empty space
        if ((spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                (spaceTempUserShareFlag && spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
//                  return resultList.get(0);
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    return resultList.get(0);
                }

//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
        }

        //user share Y sku share N
        //spaceType  is not null,creator skuType skuCode is null,
        // businessType   skuCodeCurrent is not null, creatorCurrent is null / not  empty space
        if ((spaceUserShareFlag && !spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                (spaceTempUserShareFlag && !spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
        }
        // user share N sku share N
        //spaceType  is not null,creator skuType skuCode is null,
        // businessType   creatorCurrent skuCodeCurrent is not null/ not  empty space
        if ((!spaceUserShareFlag && !spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                (!spaceTempUserShareFlag && !spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }

        }
//        config spaceType
        //12
        //spaceType  is not null,creator skuType skuCode is null,
        // businessType   creatorCurrent skuCodeCurrent is  null/   empty space
        key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + "storageUser:" + "skuCodeCurrent:";
        resultList = resultMap.get(key);
        if (resultList != null && resultList.size() > 0) {
            return resultList.get(0);
//            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
        }
//        }
        /**spaceType end*/
        return null;
//        return getSpaces(systemRuleInfo,resultMap,productDetails,CabinetCargoSpace.SpaceType.common,creator,skuCode,businessType,spaceNature);
    }


    CabinetCargoSpaceVO getSpaces(SystemRuleInfo systemRuleInfo, Map<String, List<CabinetCargoSpaceVO>> resultMap, List<ProductDetail> productDetails, CabinetCargoSpace.SpaceType spaceType, Long creator, String skuCode, StorageInventoryInout.BusinessType businessType, CabinetCargoSpace.SpaceNature spaceNature) {
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
            spaceTempMoreFlag = true;
        }
        //config spaceType &creator &sku
//        String quantityKey="quantity>0";
        //creator is not null skuCode is not null &businessType is not null& user share N sku share N
        //user&sku
        //1
        /**spaceType creator skuCode start*/
        //config spaceType &creator &sku
//        String quantityKey="quantity>0";
        //creator is not null skuCode is not null &businessType is not null& user share N sku share N
        //user&sku
        //1 spaceType creator skuCode is not null,
        // businessType creatorCurrent skuCodeCurrent is not null/not empty space
        if (CabinetCargoSpace.SpaceNature.personal.equals(spaceNature) ||
                CabinetCargoSpace.SpaceNature.common.equals(spaceNature) ||
                spaceNature == null) {
            String key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
            List<CabinetCargoSpaceVO> resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (StorageInventoryInout.BusinessType.temp.equals(businessType) && spaceTempMoreFlag) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            //2 creator is not null skuCode is not null &businessType is null& user share N sku share N& empty
            //spaceType creator skuCode  is not null,
            // businessType currentCreator currentSkuCode is null/empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + skuCode + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            /**spaceType creator skuCode end*/
            /**spaceType creator skuType start*/
            if (productDetails.size() > 0) {
                Long productTypeId = productDetails.get(0).getProductTypeId();
                if (productTypeId != null) {
                    //config sapceType & creator productType
                    //user&productType & sku share N user share N
                    //creator is not null productType is not null& businessType is not null & sku share N user share N
                    //3
//                key="spaceType:"+spaceType.getValue()+"user:"+creator+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+creator+"skuCodeCurrent:"+skuCode;
                    //spaceType creator skuType  is not null
                    // businessType creatorCurrent skuCodeCurrent is not null/not empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }

                    // productType & user is null & sku share Y user share N
                    //sku share space
                    //spaceType creator skuType businessType is not null,sku share Y/not empty space
                    //spaceType creator skuType  is not null
                    // businessType creatorCurrent  is not null,skuCodeCurrent is null/not empty space
                    if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    /**
                     //productType & user is null & user share Y  sku share N
                     //user share storage
                     if ((spaceUserShareFlag&&!StorageInventoryInout.BusinessType.temp.equals(businessType))||
                     (spaceTempUserShareFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType))){
                     key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+"skuCodeCurrent:"+skuCode;
                     resultList=resultMap.get(key);
                     if (resultList!=null&&resultList.size()>0){
                     //                          return resultList.get(0);
                     if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     if (spaceTempMoreFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                     //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                     //                            return cabinetCargoSpaceVO;
                     //                        }
                     //                    }
                     }
                     }
                     // productType & user is null &n user share Y sku share Y
                     if ((spaceUserShareFlag&&spaceSkuShareFlag&&!StorageInventoryInout.BusinessType.temp.equals(businessType))||
                     (spaceTempUserShareFlag&&spaceSkuShareFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType))){
                     key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+businessType.getValue()+"storageUser:"+"skuCodeCurrent:";
                     resultList=resultMap.get(key);
                     if (resultList!=null&&resultList.size()>0){
                     //                          return resultList.get(0);
                     if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     if (spaceTempMoreFlag&&StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     return resultList.get(0);
                     }
                     //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                     //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                     //                            return cabinetCargoSpaceVO;
                     //                        }
                     //                    }
                     }
                     }*/

                    //4 creator &productType &businessType is null & empty
                    //spaceType creator skuType  is not null，
                    // businessType creatorCurrent skuCodeCurrent is null/empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + creator + "productType:" + productTypeId + "businessType:" + "storageUser:" + "skuCodeCurrent:";
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
                        return resultList.get(0);
//                    if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                        return resultList.get(0);
//                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                    //creator is null productType&empty
                    /**
                     key="spaceType:"+spaceType.getValue()+"user:"+"productType:"+productTypeId+"businessType:"+"storageUser:";
                     resultList=resultMap.get(key);
                     if (resultList!=null&&resultList.size()>0){
                     return resultList.get(0);
                     //                    if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
                     //                        return resultList.get(0);
                     //                    }
                     //                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
                     //                        if (cabinetCargoSpaceVO.getBusinessType()==null){
                     //                            return cabinetCargoSpaceVO;
                     //                        }
                     //                    }
                     }*/
                }
            }
            /**spaceType creator skuType end*/
            /**spaceType creator start*/
            //config spaceType &creator
            //creator
            //creator is not null skuCode is null
            //5
            //spaceType creator is not null,skuCode is null
            // ,businessType creatorCurrent skuCodeCurrent is not  null/not empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            //creator is not null &sku share Y user share N
            //spaceType creator is not null,skuCode is null,
            // businessType creatorCurrent is not null,skuCodeCurrent is null/not empty space
            if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//                for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                    if (cabinetCargoSpaceVO.getBusinessType()==null){
//                        return cabinetCargoSpaceVO;
//                    }
//                }
                }
            }
            //6 creator&businessType is null & empty
            //spaceType creator is not null,skuCode is null,
            // businessType currentSkuCode currentCreator is  null/ empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + creator + "skuCode:" + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
        }
        /**spaceType creator end*/
//        config spaceType&skuCode sku share N
        //sku
        //creator is null skuCode is not null
        /**spaceType skuCode start*/
        //7
        //spaceType skuCode is not null,creator is null,
        // businessType creatorCurrent skuCodeCurrent is  not null/ not empty space
        if (CabinetCargoSpace.SpaceNature.common.equals(spaceNature) || spaceNature == null) {
            String key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
            List<CabinetCargoSpaceVO> resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
                if (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                    return resultList.get(0);
                }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            //user share Y
            //spaceType skuCode is not null,creator is null,businessType  skuCodeCurrent is not null/not empty space
            //spaceType skuCode is not null,creator is null,
            // businessType  skuCodeCurrent is  not null ,creatorCurrent is null/ not empty space
            if ((spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//                for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                    if (cabinetCargoSpaceVO.getBusinessType()==null){
//                        return cabinetCargoSpaceVO;
//                    }
//                }
                }
            }
            //8 empty
            //spaceType skuCode is not null,creator is null,businessType creatorCurrent skuCodeCurrent is  null/empty space
            //spaceType skuCode is not null,creator is null,
            // businessType  skuCodeCurrent creatorCurrent is null/  empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + skuCode + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (spaceTempMoreFlag||!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
            /**spaceType skuCode end*/
            //
            //creator is nul productType is not null storage user is not null

            /**spaceType skuType start*/
            if (productDetails.size() > 0) {
                Long productTypeId = productDetails.get(0).getProductTypeId();
                if (productTypeId != null) {
                    //config spaceType &product Type
                    //9
                    // creator &productType & user share N sku share N
                    //spaceType skuType is not null,creator is null,
                    // businessType  skuCodeCurrent creatorCurrent is  not null / not empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                        if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
                        if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                            return resultList.get(0);
                        }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                    //productType& sku share Y user share N
                    //spaceType skuType is not null,creator is null,
                    // businessType   creatorCurrent is  not null,skuCodeCurrent is null / not empty space
                    if ((spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    //creator is null &productType &user share Y sku share N
                    //spaceType skuType is not null,creator is null,
                    // businessType   skuCodeCurrent is  not null, creatorCurrent is null / not empty space
                    if ((spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    //productType & creator is null& businessType& user share Y sku share Y
                    //spaceType skuType is not null,creator is null,
                    // businessType    is  not null, creatorCurrent skuCodeCurrent is null / not empty space
                    if ((spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (spaceTempUserShareFlag && spaceSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:";
                        resultList = resultMap.get(key);
                        if (resultList != null && resultList.size() > 0) {
//                          return resultList.get(0);
                            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
                            if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                                return resultList.get(0);
                            }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                        }
                    }
                    //10 creator&productType &empty
//                key="spaceType:"+spaceType.getValue()+"user:"+creator+"productType:"+productTypeId+"businessType:"+"storageUser:"+"skuCodeCurrent:";
//                resultList=resultMap.get(key);
//                if (resultList!=null&&resultList.size()>0){
//                    return resultList.get(0);
////                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
////                        return resultList.get(0);
////                    }
////                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
////                        if (cabinetCargoSpaceVO.getBusinessType()==null){
////                            return cabinetCargoSpaceVO;
////                        }
////                    }
//                }
                    //creator is null productType&empty
                    //spaceType skuType is not null,creator is null,
                    // businessType  creatorCurrent skuCodeCurrent is null /  empty space
                    key = "spaceType:" + spaceType.getValue() + "user:" + "productType:" + productTypeId + "businessType:" + "storageUser:" + "skuCodeCurrent:";
                    resultList = resultMap.get(key);
                    if (resultList != null && resultList.size() > 0) {
                        return resultList.get(0);
//                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                        return resultList.get(0);
//                    }
//                    for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                        if (cabinetCargoSpaceVO.getBusinessType()==null){
//                            return cabinetCargoSpaceVO;
//                        }
//                    }
                    }
                }
            }
            /**spaceType skuType end*/

            /**spaceType start*/
            //config
            //creator is null productType is null skuCode is null
            //11 user share N sku share Y
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType  creatorCurrent  is not null,skuCodeCurrent is null / not  empty space
            if ((!spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (!spaceTempUserShareFlag && spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }
            }
            // user share Y sku share Y
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType    is not null,skuCodeCurrent creatorCurrent is null / not  empty space
            if ((spaceUserShareFlag && spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempUserShareFlag && spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:";
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                  return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        return resultList.get(0);
                    }

//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }
            }

            //user share Y sku share N
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType   skuCodeCurrent is not null, creatorCurrent is null / not  empty space
            if ((spaceUserShareFlag && !spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (spaceTempUserShareFlag && !spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if (spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }
            }
            // user share N sku share N
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType   creatorCurrent skuCodeCurrent is not null/ not  empty space
            if ((!spaceUserShareFlag && !spaceSkuShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                    (!spaceTempUserShareFlag && !spaceTempSkuShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + businessType.getValue() + "storageUser:" + creator + "skuCodeCurrent:" + skuCode;
                resultList = resultMap.get(key);
                if (resultList != null && resultList.size() > 0) {
//                return resultList.get(0);
                    if (!StorageInventoryInout.BusinessType.temp.equals(businessType)) {
                        return resultList.get(0);
                    }
                    if ((spaceTempMoreFlag && StorageInventoryInout.BusinessType.temp.equals(businessType))) {
                        return resultList.get(0);
                    }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
                }

            }
//        config spaceType
            //12
            //spaceType  is not null,creator skuType skuCode is null,
            // businessType   creatorCurrent skuCodeCurrent is  null/   empty space
            key = "spaceType:" + spaceType.getValue() + "user:" + "skuCode:" + "businessType:" + "storageUser:" + "skuCodeCurrent:";
            resultList = resultMap.get(key);
            if (resultList != null && resultList.size() > 0) {
                return resultList.get(0);
//            if (!StorageInventoryInout.BusinessType.temp.equals(businessType)){
//                return resultList.get(0);
//            }
//            for (CabinetCargoSpaceVO cabinetCargoSpaceVO:resultList){
//                if (cabinetCargoSpaceVO.getBusinessType()==null){
//                    return cabinetCargoSpaceVO;
//                }
//            }
            }
        }
        /**spaceType end*/

        return null;
    }


    @Override
    public CabinetCargoSpaceVO getUsedSpaces(UseInventoryInoutDetailForm useInventoryInoutDetailForm, StorageInventoryInout.BusinessType businessType) {
        Long creator = JwtUtils.getLoginUserId();


        Long principal = null;
        Long productTypeId = null;
        if (CabinetCargoSpace.SpaceNature.personal.equals(useInventoryInoutDetailForm.getStorageType())) {
            principal = JwtUtils.getLoginUserId();
        } else if (CabinetCargoSpace.SpaceNature.specialClass.equals(useInventoryInoutDetailForm.getStorageType())) {
            Map paramMap = new HashMap();
            paramMap.put("skuCode", useInventoryInoutDetailForm.getSkuCode());
            List<ProductDetailVO> productDetailVOS = productDetailService.list4app(paramMap);
            if (productDetailVOS.size() == 0) {
                throw new BusinessException("未找到产品SKU");
            }
            productTypeId = productDetailVOS.get(0).getProductTypeId();
        } else if (CabinetCargoSpace.SpaceNature.common.equals(useInventoryInoutDetailForm.getStorageType())) {

//        }else if(CabinetCargoSpace.SpaceNature.repair.equals(useInventoryInoutDetailForm.getStorageType())){
//
//        }else if(CabinetCargoSpace.SpaceNature.recycle.equals(useInventoryInoutDetailForm.getStorageType())){
//
        } else {
            throw new BusinessException("货位存贮性质参数错误");
        }

        if (StorageInventoryInout.BusinessType.recycle.equals(businessType) || StorageInventoryInout.BusinessType.repair.equals(businessType)) {
            List<CabinetCargoSpaceVO> spaceVOS = cargoSpaceService.getUsedSpace(useInventoryInoutDetailForm.getCabCode(), businessType.getValue(), useInventoryInoutDetailForm.getQuantity(), useInventoryInoutDetailForm.getSkuCode(), useInventoryInoutDetailForm.getStorageType().name(), useInventoryInoutDetailForm.getStorageType().getValue(), principal, productTypeId, creator);
            if (spaceVOS.size() > 0) {
                return spaceVOS.get(0);
            }
        }

        return null;
    }

    @Override
    public JsonResult<List<CabinetCargoSpaceVO>> getCheckedSpace(UseInventoryInoutDetailForm useInventoryInoutDetailForm, StorageInventoryInout.BusinessType businessType) {
        if (CabinetCargoSpace.SpaceNature.repair.equals(useInventoryInoutDetailForm.getStorageType())) {

        } else if (CabinetCargoSpace.SpaceNature.recycle.equals(useInventoryInoutDetailForm.getStorageType())) {

        } else {
            return JsonResult.fail("货位存贮性质参数错误");
        }
        List<CabinetCargoSpaceVO> recycleRepairSpaces = cargoSpaceService.getRecycleRepairSpaces(useInventoryInoutDetailForm.getCabCode(), useInventoryInoutDetailForm.getStorageType().getValue(), null, null);
        if (recycleRepairSpaces.size() == 0) {
            if (CabinetCargoSpace.SpaceNature.repair.equals(useInventoryInoutDetailForm.getStorageType())) {
                return JsonResult.fail("请先设置维修的库位");
            } else if (CabinetCargoSpace.SpaceNature.recycle.equals(useInventoryInoutDetailForm.getStorageType())) {
                return JsonResult.fail("请先设置回收的库位");
            }
        }

        return JsonResult.success(recycleRepairSpaces);
    }

    private Integer getSumQuantityBySpace(List<StorageInventorySpace> spaceInventoryList) {
        Integer sum = 0;
        for (StorageInventorySpace storageInventorySpace : spaceInventoryList) {
            sum += storageInventorySpace.getQuantity();
        }
        return sum;
    }

    @Transactional
    void saveDetail(List<UseInventoryInoutDetailForm> list, Long storageInventoryInoutId, String inOutTypeName, StorageInventoryInout.BusinessType businessType, boolean isCheck, String deviceCode, StorageInventoryInout.BusinessDetailType businessDetailType, Long checkResultId, StorageInventoryInout.BusinessType businessTypeChecked, Long storageInventoryCheckId) {
        List<Cabinet> cabinets=cabinetService.list(new QueryWrapper<Cabinet>().eq("code",list.get(0).getCabCode()));
        String mainCabCode=null;
        if (cabinets.size()>0){
            mainCabCode=cabinets.get(0).getBelongCabinet();
        }
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag=true;
        }
        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String channelCode=JwtUtils.getChannelCode();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        if (CollectionUtils.isNotEmpty(list)) {
            if (UseInventoryInout.Type.in.name().equals(inOutTypeName) &&
                    !isCheck
                    && (StorageInventoryInout.BusinessType.repair.equals(businessType) || StorageInventoryInout.BusinessType.recycle.equals(businessType))
            ) {
                saveCheckData(list, businessType, storageInventoryInoutId, businessDetailType);
            }
            for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                if(null == useInventoryInoutDetailForm.getPackId() || useInventoryInoutDetailForm.getPackId().equals(0)) {
                    //useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                    //useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                    //useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                    //useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                    throw new BusinessException("请选择合适的包装方案");
                }
                //else{
                ProductPackVO productPackVO =productPackService.get4appById(useInventoryInoutDetailForm.getPackId());
                if(null != productPackVO) {
                    useInventoryInoutDetailForm.setPackId(productPackVO.getId());
                    useInventoryInoutDetailForm.setPackName(productPackVO.getName());
                    useInventoryInoutDetailForm.setUnitName(productPackVO.getPackUnitName());
                    useInventoryInoutDetailForm.setQuantityPackUnit(productPackVO.getBaseRate());
                }else{
                    useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                    useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                    useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                    useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
                //}
                if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getDeviceCode())){
                    deviceCode=useInventoryInoutDetailForm.getDeviceCode();
                }
                StorageInventoryInoutDetail storageInventoryInoutDetail = new StorageInventoryInoutDetail();
                BeanUtils.copyProperties(useInventoryInoutDetailForm, storageInventoryInoutDetail);
                storageInventoryInoutDetail.setCompanyId(enterpriseId);
                storageInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                storageInventoryInoutDetail.setId(null);
                storageInventoryInoutDetail.setCreator(creator);
                storageInventoryInoutDetail.setCreatorName(creatorName);
                storageInventoryInoutDetail.setOperationType(StorageInventoryInoutDetail.OperationType.jsonCreator(inOutTypeName));
                storageInventoryInoutDetail.setBusinessType(StorageInventoryInoutDetail.BusinessType.jsonCreator(businessType.name()));
                storageInventoryInoutDetail.setInoutId(storageInventoryInoutId);
                storageInventoryInoutDetail.setChannelCode(channelCode);
                storageInventoryInoutDetail.setQuantityPack(storageInventoryInoutDetail.getQuantity());


//                List<StorageInventorySpace> spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("business_type",businessType.getValue()));
//                List<StorageInventorySpace> spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
                List<CabinetCargoSpace> cabinetCargoSpaces = cargoSpaceService.list(new QueryWrapper<CabinetCargoSpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("code", useInventoryInoutDetailForm.getSpaceCode()));
                if (cabinetCargoSpaces.size() == 0) {
                    throw new BusinessException("未找到库位,柜子编号:"+useInventoryInoutDetailForm.getCabCode()+",库位编号:"+useInventoryInoutDetailForm.getSpaceCode());
                }
//                if (CabinetCargoSpace.SpaceNature.personal.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
//                    if (!creator.equals(cabinetCargoSpaces.get(0).getPrincipal())){
//                        throw new BusinessException("柜子编号["+cabinetCargoSpaces.get(0).getCode()+"]为用户的专人存贮,其他用户不能打开");
//                    }
//                }
                List<StorageInventorySpace> spaceInventoryList = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
                    /**
                     if (CabinetCargoSpace.SpaceNature.common.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     if (StorageInventoryInout.BusinessType.temp.equals(businessType)&&spaceInventoryList.size()!=0&&spaceInventoryList.get(0).getQuantity()>0){
                     throw new BusinessException("请选择空的库位");
                     }
                     }else if(CabinetCargoSpace.SpaceNature.personal.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     if (!creator.equals(cabinetCargoSpaces.get(0).getPrincipal())){
                     throw new BusinessException("柜子编号["+cabinetCargoSpaces.get(0).getCode()+"]为用户的专人存贮,其他用户不能打开");
                     }

                     }else if(CabinetCargoSpace.SpaceNature.specialClass.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     Map paramMap=new HashMap();
                     paramMap.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
                     List<ProductDetailVO> productDetailVOS=productDetailService.list4app(paramMap);
                     if (productDetailVOS.size()==0){
                     throw new BusinessException("未找到产品");
                     }
                     if (cabinetCargoSpaces.get(0).getSpaceProductType()!=null&&!cabinetCargoSpaces.get(0).getSpaceProductType().equals(productDetailVOS.get(0).getProductTypeId())){
                     throw new BusinessException("此库位不能存储此产品类型["+productDetailVOS.get(0).getProductTypeName()+"]");
                     }
                     }else if(CabinetCargoSpace.SpaceNature.repair.equals(cabinetCargoSpaces.get(0).getSpaceNature())) {

                     }else if(CabinetCargoSpace.SpaceNature.recycle.equals(cabinetCargoSpaces.get(0).getSpaceNature())) {

                     }else{
                     throw new BusinessException("请先设置货道存贮性质");
                     }

                     if (spaceInventoryList.size()>0&&!spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())){
                     throw new BusinessException("此库位之前存贮的是["+spaceInventoryList.get(0).getBusinessType().getDesc()+"],不能再存贮["+businessType.getDesc()+"]");
                     }
                     if (spaceInventoryList.size()>0){
                     Integer sum=getSumQuantityBySpace(spaceInventoryList);
                     if (sum>=cabinetCargoSpaces.get(0).getQuantity()){
                     throw new BusinessException("柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]库位["+useInventoryInoutDetailForm.getSpaceCode()+"]已经存满");
                     }
                     }
                     List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));
                     if (skuInventoryUserList.size()>0&&!creator.equals(skuInventoryUserList.get(0).getCreator())){
                     throw new BusinessException("此库位已被他人占用");
                     }*/
                    /**
                     if (StorageInventoryInout.BusinessType.temp.equals(businessType)&&spaceInventoryList.size()!=0&&spaceInventoryList.get(0).getQuantity()>0){
                     throw new BusinessException("请选择空的库位");
                     }
                     if(CabinetCargoSpace.SpaceNature.personal.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     if (!creator.equals(cabinetCargoSpaces.get(0).getPrincipal())){
                     throw new BusinessException("柜子编号["+cabinetCargoSpaces.get(0).getCode()+"]为用户的专人存贮,其他用户不能打开");
                     }

                     }
                     if (cabinetCargoSpaces.get(0).getSpaceProductType()!=null){
                     Map paramMap=new HashMap();
                     paramMap.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
                     List<ProductDetailVO> productDetailVOS=productDetailService.list4app(paramMap);
                     if (productDetailVOS.size()==0){
                     throw new BusinessException("未找到产品");
                     }
                     if(!cabinetCargoSpaces.get(0).getSpaceProductType().equals(productDetailVOS.get(0).getProductTypeId())){
                     throw new BusinessException("此库位不能存储此产品类型["+productDetailVOS.get(0).getProductTypeName()+"]");
                     }

                     }
                     if (spaceInventoryList.size()>0&&!spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())){
                     throw new BusinessException("此库位之前存贮的是["+spaceInventoryList.get(0).getBusinessType().getDesc()+"],不能再存贮["+businessType.getDesc()+"]");
                     }
                     if (spaceInventoryList.size()>0){
                     Integer sum=getSumQuantityBySpace(spaceInventoryList);
                     if (sum>=cabinetCargoSpaces.get(0).getQuantity()){
                     throw new BusinessException("柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]库位["+useInventoryInoutDetailForm.getSpaceCode()+"]已经存满");
                     }
                     }
                     List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));
                     if (skuInventoryUserList.size()>0&&!creator.equals(skuInventoryUserList.get(0).getCreator())){
                     throw new BusinessException("此库位已被他人占用");
                     }*/
                    log.info("{}", StorageInventoryInout.BusinessType.temp.equals(businessType));
                    if (cabinetCargoSpaces.get(0).getSpaceType() != null &&
                            (CabinetCargoSpace.SpaceType.common.equals(cabinetCargoSpaces.get(0).getSpaceType()) ||
                                    CabinetCargoSpace.SpaceType.temp.equals(cabinetCargoSpaces.get(0).getSpaceType())) &&
                            (StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()))

                    ) {
                        int count = storageInventoryKnifeService.count(new QueryWrapper<StorageInventoryKnife>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                        if (!spaceTempMoreFlag&&StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()) && StorageInventoryInout.BusinessType.temp.equals(businessType) && count > 0) {
                            throw new BusinessException("请选择空的库位或者设置暂存允许多存");
                        }
                    }

                    log.info("{},{}", creator, cabinetCargoSpaces.get(0).getPrincipal());
                    if (StringUtils.isNotBlank(cabinetCargoSpaces.get(0).getPrincipal())) {
                        if (!(","+cabinetCargoSpaces.get(0).getPrincipal()+",").contains(","+creator+",")) {
                            throw new BusinessException("柜子编号[" + cabinetCargoSpaces.get(0).getCode() + "]为用户的专人存贮,其他用户不能打开");
                        }

                    }
                    if (StringUtils.isNotBlank(cabinetCargoSpaces.get(0).getSkuCode())) {
                        if (!useInventoryInoutDetailForm.getSkuCode().equals(cabinetCargoSpaces.get(0).getSkuCode())) {
                            throw new BusinessException("此库位不能存储此产品SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]的产品");
                        }
                    }
                    if (cabinetCargoSpaces.get(0).getSpaceProductType() != null && cabinetCargoSpaces.get(0).getSpaceProductType() != 0) {
                        Map paramMap = new HashMap();
                        paramMap.put("skuCode4app", useInventoryInoutDetailForm.getSkuCode());
                        List<ProductDetailVO> productDetailVOS = productDetailService.list4app(paramMap);
                        if (productDetailVOS.size() == 0) {
                            throw new BusinessException("未找到产品");
                        }
                        if (!cabinetCargoSpaces.get(0).getSpaceProductType().equals(productDetailVOS.get(0).getProductTypeId())) {
                            throw new BusinessException("此库位不能存储此产品类型[" + productDetailVOS.get(0).getProductTypeName() + "]");
                        }

                    }
                    if (cabinetCargoSpaces.get(0).getSpaceType() != null && !CabinetCargoSpace.SpaceType.common.equals(cabinetCargoSpaces.get(0).getSpaceType())) {
                        if (!cabinetCargoSpaces.get(0).getSpaceType().name().equals(businessType.name())
                        ) {
                            throw new BusinessException("此库位只能存贮[" + cabinetCargoSpaces.get(0).getSpaceType().getDesc() + "],不能再存贮[" + businessType.getDesc() + "]");
                        }
                    }
                    if (spaceInventoryList.size() > 0 && !spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())) {
                        throw new BusinessException("此库位之前存贮的是[" + spaceInventoryList.get(0).getBusinessType().getDesc() + "],不能再存贮[" + businessType.getDesc() + "]");
                    }
                    if (spaceInventoryList.size() > 0) {
                        Integer sum = getSumQuantityBySpace(spaceInventoryList);
                        sum += useInventoryInoutDetailForm.getQuantity();
                        if (sum > cabinetCargoSpaces.get(0).getQuantity()) {
                            throw new BusinessException("柜子编号[" + useInventoryInoutDetailForm.getCabCode() + "]库位[" + useInventoryInoutDetailForm.getSpaceCode() + "]已经存满");
                        }
                    }
                    /**
                    List<StorageInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                    if (((!spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (!spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)))
                            && skuInventoryUserList.size() > 0 && !creator.equals(skuInventoryUserList.get(0).getCreator())) {
                        throw new BusinessException("此库位已被他人占用");
                    }*/
                    log.info("{}", StorageInventoryInout.BusinessType.temp.equals(businessType));
                    if (cabinetCargoSpaces.get(0).getSpaceType() != null &&
                            (CabinetCargoSpace.SpaceType.common.equals(cabinetCargoSpaces.get(0).getSpaceType()) ||
                                    CabinetCargoSpace.SpaceType.temp.equals(cabinetCargoSpaces.get(0).getSpaceType())) &&
                            (StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()))

                    ) {
                        int count = storageInventoryKnifeService.count(new QueryWrapper<StorageInventoryKnife>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                        if (!spaceTempMoreFlag&&StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()) && StorageInventoryInout.BusinessType.temp.equals(businessType) && count > 0) {
                            throw new BusinessException("请选择空的库位或者设置暂存允许多存");
                        }
                    }

                    log.info("{},{}", creator, cabinetCargoSpaces.get(0).getPrincipal());
                    if (StringUtils.isNotBlank(cabinetCargoSpaces.get(0).getPrincipal())) {
                        if (!(","+cabinetCargoSpaces.get(0).getPrincipal()+",").contains(","+creator+",")) {
                            throw new BusinessException("柜子编号[" + cabinetCargoSpaces.get(0).getCode() + "]为用户的专人存贮,其他用户不能打开");
                        }

                    }
                }

                List<StorageInventoryProduct> skuInventoryList = inventoryProductService.list(new QueryWrapper<StorageInventoryProduct>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("business_type", businessType.getValue()).eq("enterprise_code", enterpriseCode));
                List<StorageSingleInventoryProduct> skuSingleInventoryList = storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("business_type", businessType.getValue()));

                spaceInventoryList = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                if (UseInventoryInout.Type.out.name().equals(inOutTypeName)) {
//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }
//                    if (skuSingleInventoryList.size()==0){
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]上的SKU["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }

//                    spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));

//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("creator",useInventoryInoutDetailForm.getCreator()));
//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));
                    List<StorageInventoryKnife> skuInventoryKnifeList = storageInventoryKnifeService.list(new QueryWrapper<StorageInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));

                    if (skuInventoryKnifeList.size() == 0) {
                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(), "未找到柜子编号[" + useInventoryInoutDetailForm.getCabCode() + "]库位[" + useInventoryInoutDetailForm.getSpaceCode() + "]上的SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]刀具产品数据");
                    } else {

                        useInventoryInoutDetailForm.setRemainingTime(skuInventoryKnifeList.get(0).getRemainingTime());
                        useInventoryInoutDetailForm.setLifeUnit(skuInventoryKnifeList.get(0).getLifeUnit());
                        useInventoryInoutDetailForm.setSettingTime(skuInventoryKnifeList.get(0).getSettingTime());
                        useInventoryInoutDetailForm.setParentLabelCode(skuInventoryKnifeList.get(0).getParentLabelCode());
                        useInventoryInoutDetailForm.setPrice(skuInventoryKnifeList.get(0).getPrice());
                        storageInventoryInoutDetail.setRemainingTime(useInventoryInoutDetailForm.getRemainingTime());
                        if (useInventoryInoutDetailForm.getLifeUnit()!=null){
                            storageInventoryInoutDetail.setLifeUnit(StorageInventoryInoutDetail.LifeUnit.jsonCreator(useInventoryInoutDetailForm.getLifeUnit().name()));
                        }
                        storageInventoryInoutDetail.setSettingTime(useInventoryInoutDetailForm.getSettingTime());
                        if (StringUtils.isBlank(deviceCode)) {
                            deviceCode = skuInventoryKnifeList.get(0).getDeviceCode();
                            useInventoryInoutDetailForm.setDeviceCode(deviceCode);
                        }
                        List<StorageInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id", skuInventoryKnifeList.get(0).getStorageInventoryUserId()));
                        if (skuInventoryUserList.size() == 0) {
//                            throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]库位["+useInventoryInoutDetailForm.getSpaceCode()+"]上的SKU编号["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
                        }
                        storageInventoryKnifeService.remove(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));


                        Integer quantity = useInventoryInoutDetailForm.getQuantity();
                        if (quantity <= 0) {
                            throw new BusinessException("领取数量异常");
                        }
                        if (quantity > 0) {
                            quantity = -1 * quantity;
                        }
                        Integer quantityPack=quantity;
                        if (skuInventoryUserList.size() > 0) {
                            if (StringUtils.isBlank(deviceCode)) {
                                deviceCode = skuInventoryUserList.get(0).getDeviceCode();
                                useInventoryInoutDetailForm.setDeviceCode(deviceCode);
                            }
                            Integer currentQuantity = skuInventoryUserList.get(0).getQuantity();
                            Integer newQuantity = currentQuantity + quantity;
                            if (newQuantity < 0) {
//                                throw new BusinessException("SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品库存不足");
                            }

                            StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                            storageInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                        storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
//                        storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventoryUser.setQuantity(newQuantity);
                            Integer currentQuantityPack=skuInventoryUserList.get(0).getQuantityPack();
                            if (currentQuantityPack==null){
                                currentQuantityPack=0;
                            }
                            storageInventoryUser.setQuantityPack(currentQuantityPack+quantityPack);
                            if (newQuantity <= 0) {
                                storageInventoryUser.setBusinessType(null);
//                            storageInventoryUser.setSkuCode(null);
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            } else {
//                            storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                                inventoryUserService.updateById(storageInventoryUser);
                            }
                            storageInventoryInoutDetail.setQuantityUserCurrent(currentQuantity);
                            storageInventoryInoutDetail.setQuantityUserAfter(currentQuantity+quantity);

                            /**
                            if (spaceInventoryList.size() > 0) {
                                storageInventoryInoutDetail.setQuantityCurrent(spaceInventoryList.get(0).getQuantity());
                                storageInventoryInoutDetail.setQuantityAfter(spaceInventoryList.get(0).getQuantity() + quantity);
                            } else {
                                if(skuInventoryList.size()>0){
                                    storageInventoryInoutDetail.setQuantityCurrent(skuInventoryList.get(0).getQuantity());
                                    storageInventoryInoutDetail.setQuantityAfter(skuInventoryList.get(0).getQuantity() + quantity);
                                }
                            }*/
                        }


                        storageInventoryInoutDetail.setQuantity(quantity);
                        storageInventoryInoutDetail.setCreator(useInventoryInoutDetailForm.getCreator());
                        storageInventoryInoutDetail.setCreatorName(useInventoryInoutDetailForm.getCreatorName());
                        storageInventoryInoutDetail.setModifier(creator);
                        storageInventoryInoutDetail.setModifierName(creatorName);

//                        baseMapper.insert(storageInventoryInoutDetail);
//                        useInventoryInoutDetailForm.setLabelCode(skuInventoryUserList.get(0).getLabelCode());
//                        if (StringUtils.isNotBlank(skuInventoryUserList.get(0).getLabelCode())){
//                            UseInventoryUserKnifeInout useInventoryUserKnifeInout=new UseInventoryUserKnifeInout();
//                            useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
//                            useInventoryUserKnifeInout.setCode(skuInventoryUserList.get(0).getLabelCode());
//                            useInventoryUserKnifeInout.setStorageInventoryInoutId(inventoryInoutId);
//                            useInventoryUserKnifeInout.setStorageInventoryUserId(storageInventoryUser.getId());
//                            useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
////                        useInventoryUserKnifeInout.setUseInventoryInoutId()
//                            useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
//                        }
                    }
                    Integer quantity = useInventoryInoutDetailForm.getQuantity();
                    if (quantity <= 0) {
                        throw new BusinessException("取数量参数异常");
                    }
                    if (quantity > 0) {
                        quantity = -1 * quantity;
                    }
                    Integer quantityPack=quantity;
                    if (spaceInventoryList.size() > 0) {
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]货道["+useInventoryInoutDetailForm.getSpaceCode()+"]上的SKU编号["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }else{


                        Integer currentQuantity = spaceInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                            throw new BusinessException("SKU编号["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品库存不足");
                        }

                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setId(spaceInventoryList.get(0).getId());
//                        storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                        storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
//                        storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setQuantity(newQuantity);
                        Integer currentQuantityPack=spaceInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventorySpace.setQuantityPack(currentQuantityPack+quantityPack);
                        if (newQuantity <= 0) {
                            storageInventorySpace.setBusinessType(null);
//                            storageInventorySpace.setSkuCode(null);
                            inventorySpaceService.removeById(spaceInventoryList.get(0).getId());
                        } else {
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                            inventorySpaceService.updateById(storageInventorySpace);
                        }
                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(currentQuantity+quantity);

                        storageInventoryInoutDetail.setQuantityPackCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackAfter(currentQuantityPack+quantityPack);

                        /**
                        if (skuSingleInventoryList.size() > 0) {
                            StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                            storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
//                            storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                            storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + quantity);
                            if (storageSingleInventoryProduct.getQuantity() <= 0) {
                                storageSingleInventoryProduct.setBusinessType(null);
//                            storageSingleInventoryProduct.setSkuCode(null);
                                storageSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                            } else {
//                                storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                                storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);
                            }
                        }

                        if (skuInventoryList.size() > 0) {
                            StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                            storageInventoryProduct.setId(skuInventoryList.get(0).getId());
//                            storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + quantity);
                            if (storageInventoryProduct.getQuantity() <= 0) {
                                storageInventoryProduct.setBusinessType(null);
//                            storageInventoryProduct.setSkuCode(null);
                                inventoryProductService.removeById(skuInventoryList.get(0).getId());
                            } else {
//                                storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                                inventoryProductService.updateById(storageInventoryProduct);
                            }
                        }*/
//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }
                    if (skuSingleInventoryList.size() > 0) {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
//                            storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                            storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + quantity);
                        Integer currentQuantityPack=skuSingleInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageSingleInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        if (storageSingleInventoryProduct.getQuantity() <= 0) {
//                            storageSingleInventoryProduct.setBusinessType(null);
//                            storageSingleInventoryProduct.setSkuCode(null);
                            storageSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                        } else {
//                                storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                            storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);
                        }
                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());

                        storageInventoryInoutDetail.setQuantityPackSingleCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackSingleCabAfter(storageSingleInventoryProduct.getQuantityPack());
                    }

                    if (skuInventoryList.size() > 0) {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setId(skuInventoryList.get(0).getId());
//                            storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + quantity);
                        Integer currentQuantityPack=skuInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        if (storageInventoryProduct.getQuantity() <= 0) {
//                            storageInventoryProduct.setBusinessType(null);
//                            storageInventoryProduct.setSkuCode(null);
                            inventoryProductService.removeById(skuInventoryList.get(0).getId());
                        } else {
//                                storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                            inventoryProductService.updateById(storageInventoryProduct);
                        }
                        storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());

                        storageInventoryInoutDetail.setQuantityPackCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackCabAfter(storageInventoryProduct.getQuantityPack());
                    }
                    storageInventoryInoutDetail.setMainCabCode(mainCabCode);

                    baseMapper.insert(storageInventoryInoutDetail);
                } else if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
                    String parentLabelCode=null;
                    if (!isCheck){
                        List<UseInventoryKnife> skuInventoryKnifeList = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                        if (skuInventoryKnifeList.size() == 0) {
                            throw new BusinessException("未找到SKU[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品");
                        }
                        parentLabelCode=skuInventoryKnifeList.get(0).getParentLabelCode();
                        if (StringUtils.isBlank(deviceCode)){
                            useInventoryInoutDetailForm.setDeviceCode(skuInventoryKnifeList.get(0).getDeviceCode());
                        }
                    }else{
                        parentLabelCode=useInventoryInoutDetailForm.getParentLabelCode();
                    }

                    if (!isCheck && (systemRuleInfo != null && systemRuleInfo.getAbFlag() != null && !systemRuleInfo.getAbFlag())) {
                        if (!creator.equals(useInventoryInoutDetailForm.getCreator())) {
                            throw new BusinessException("系统设置不允许A借B还");
                        }
                    }

//                    Integer quantity=useInventoryInoutDetailForm.getQuantity();
                    if (useInventoryInoutDetailForm.getQuantity() <= 0) {
                        throw new BusinessException("存数量参数异常");
                    }
                    Integer quantityPack=useInventoryInoutDetailForm.getQuantity();


//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("creator",creator));
//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));

//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));

//                    if (skuInventoryUserList.size()==0){
//                        Integer currentQuantity=0;
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                    StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                    storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    storageInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                    storageInventoryUser.setCreator(creator);
                    storageInventoryUser.setCreatorName(creatorName);
                    storageInventoryUser.setCompanyId(enterpriseId);
                    storageInventoryUser.setDeviceCode(deviceCode);
                    storageInventoryUser.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                    storageInventoryUser.setRemark(storageInventoryUser.getBusinessTypeDesc());
                    storageInventoryUser.setWorkOrderId(list.get(0).getWorkOrderId());
                    storageInventoryUser.setProcessId(list.get(0).getProcessId());
                    storageInventoryUser.setEnterpriseCode(enterpriseCode);
                    storageInventoryUser.setRoleId(roleId);
                    storageInventoryUser.setRoleName(roleName);
                    storageInventoryUser.setChannelCode(channelCode);
                    storageInventoryUser.setDepartmentId(departmentId);
                    storageInventoryUser.setDepartmentName(departmentName);
                    /**
                     * 默认包装单位 一粒/片
                     */
                    storageInventoryUser.setPackId(useInventoryInoutDetailForm.getPackId());
                    storageInventoryUser.setPackName(useInventoryInoutDetailForm.getPackName());
                    storageInventoryUser.setUnitName(useInventoryInoutDetailForm.getUnitName());
                    storageInventoryUser.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                    storageInventoryUser.setPrice(useInventoryInoutDetailForm.getPrice());
                    storageInventoryUser.setQuantityPack(useInventoryInoutDetailForm.getQuantity());
                    BigDecimal total=null;
                    if (useInventoryInoutDetailForm.getPrice()!=null){
                        total=useInventoryInoutDetailForm.getPrice().multiply(BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()));
                    }
                    storageInventoryUser.setTotal(total);
                    inventoryUserService.save(storageInventoryUser);

                    storageInventoryInoutDetail.setQuantityUserCurrent(0);
                    storageInventoryInoutDetail.setQuantityUserAfter(useInventoryInoutDetailForm.getQuantity());
                    storageInventoryInoutDetail.setStorageInventoryUserId(storageInventoryUser.getId());

                    int count = storageInventoryKnifeService.count(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                    log.info("storage inventory knife count:{}", count);
                    if (count > 0) {
                        storageInventoryKnifeService.remove(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                    }

                    StorageInventoryKnife storageInventoryKnife = new StorageInventoryKnife();
                    storageInventoryKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    storageInventoryKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    storageInventoryKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    storageInventoryKnife.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    storageInventoryKnife.setBusinessType(StorageInventoryKnife.BusinessType.jsonCreator(businessType.name()));
                    storageInventoryKnife.setCreator(creator);
                    storageInventoryKnife.setCreatorName(creatorName);
                    storageInventoryKnife.setCompanyId(enterpriseId);
                    storageInventoryKnife.setDeviceCode(deviceCode);
                    storageInventoryKnife.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                    storageInventoryKnife.setStorageInventoryUserId(storageInventoryUser.getId());

                    storageInventoryKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                    storageInventoryKnife.setProcessId(list.get(0).getProcessId());
                    storageInventoryKnife.setEnterpriseCode(enterpriseCode);
                    storageInventoryKnife.setBusinessDetailType(StorageInventoryKnife.BusinessDetailType.jsonCreator(businessDetailType.name()));
                    storageInventoryKnife.setRemark(storageInventoryKnife.getBusinessDetailTypeDesc());
                    storageInventoryKnife.setCategoryId(useInventoryInoutDetailForm.getCategoryId());
                    storageInventoryKnife.setDepartmentId(departmentId);
                    storageInventoryKnife.setDepartmentName(departmentName);
                    storageInventoryKnife.setRoleId(roleId);
                    storageInventoryKnife.setRoleName(roleName);
                    storageInventoryKnife.setChannelCode(channelCode);
                    storageInventoryKnife.setParentLabelCode(parentLabelCode);
                    storageInventoryKnife.setMainCabCode(mainCabCode);
                    storageInventoryKnife.setPrice(useInventoryInoutDetailForm.getPrice());
                    if (!isCheck) {
                        if (useInventoryInoutDetailForm.getUseTime()!=null&&useInventoryInoutDetailForm.getUseTime()>0){
                            List<UseInventoryKnife> useInventoryKnives = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                            if (useInventoryKnives.size() == 0) {
//                            throw new BusinessException("未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
                            }
                            if (useInventoryKnives.size() > 0) {
                                if (useInventoryKnives.get(0).getSettingTime() != null&&useInventoryKnives.get(0).getRemainingTime()!=null) {
                                    if (useInventoryKnives.get(0).getLifeUnit() != null) {
                                        storageInventoryKnife.setLifeUnit(StorageInventoryKnife.LifeUnit.jsonCreator(useInventoryKnives.get(0).getLifeUnit().name()));
                                    }
                                    storageInventoryKnife.setSettingTime(useInventoryKnives.get(0).getSettingTime());
                                    storageInventoryKnife.setRemainingTime(useInventoryKnives.get(0).getRemainingTime()-useInventoryInoutDetailForm.getUseTime());
                                } else {
                                    List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                                    if (productDetails.size() > 0) {
                                        if (productDetails.get(0).getLifeSpan() != null) {
//                                        useInventoryUserKnife.setInitTime(productDetails.get(0).getLifeSpan());
//                                        useInventoryUserKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                            storageInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan()-useInventoryInoutDetailForm.getUseTime());
                                            storageInventoryKnife.setSettingTime(productDetails.get(0).getLifeSpan());

//                                        useInventoryUserKnifeInout.setInitTime(productDetails.get(0).getLifeSpan());
//                                        useInventoryUserKnifeInout.setRemainingTime(productDetails.get(0).getLifeSpan());
                                        }

                                        if (productDetails.get(0).getLifeUnit() != null) {
                                            storageInventoryKnife.setLifeUnit(StorageInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
//                                        useInventoryUserKnife.setLifeUnit(UseInventoryUserKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
//                                        useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                        }

                                    }
                                }

                            }
                        }

                    } else {
                        storageInventoryKnife.setSettingTime(useInventoryInoutDetailForm.getSettingTime());
                        storageInventoryKnife.setRemainingTime(useInventoryInoutDetailForm.getRemainingTime());
                        storageInventoryKnife.setLifeUnit(useInventoryInoutDetailForm.getLifeUnit());
                    }

                    storageInventoryInoutDetail.setSettingTime(storageInventoryKnife.getSettingTime());
                    storageInventoryInoutDetail.setRemainingTime(storageInventoryKnife.getRemainingTime());
                    storageInventoryInoutDetail.setUseTime(useInventoryInoutDetailForm.getUseTime());
                    storageInventoryInoutDetail.setRemark(businessDetailType.getDesc());
                    if (storageInventoryKnife.getLifeUnit()!=null){
                        storageInventoryInoutDetail.setLifeUnit(StorageInventoryInoutDetail.LifeUnit.jsonCreator(storageInventoryKnife.getLifeUnit().name()));
                    }
                    storageInventoryKnifeService.save(storageInventoryKnife);

                    if (isCheck) {


                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                        useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        if (StringUtils.isNotBlank(list.get(0).getRemark())){
                            useInventoryUserKnife.setRemark(list.get(0).getRemark());
                        }else{
                            useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                        }

                        useInventoryUserKnifeService.update(useInventoryUserKnife, new QueryWrapper<UseInventoryUserKnife>().eq("code", useInventoryInoutDetailForm.getLabelCode()));

//                        List<StorageInventoryCheck> storageInventoryChecks=storageInventoryCheckService.list(new QueryWrapper<StorageInventoryCheck>().eq("cab_code",isCheck?useInventoryInoutDetailForm.getCheckCabCode():useInventoryInoutDetailForm.getCabCode()).eq("space_code",isCheck?useInventoryInoutDetailForm.getCheckSpaceCode():useInventoryInoutDetailForm.getSpaceCode()).eq("status",StorageInventoryCheck.Status.created.getValue()));
                        UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();
                        useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
                        useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUserKnifeInout.setStorageInventoryUserId(storageInventoryUser.getId());
                        useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
                        useInventoryUserKnifeInout.setCheckResultId(checkResultId);
//                        useInventoryUserKnifeInout.setStorageInventoryCheckId(storageInventoryChecks.get(0).getId());
                        useInventoryUserKnifeInout.setStorageInventoryCheckId(storageInventoryCheckId);
//                        useInventoryUserKnifeInout.setCellInventoryInoutId(cellInventoryInoutId);
//                        useInventoryUserKnifeInout.setDeviceCode(deviceCode);
                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
                        useInventoryUserKnifeInout.setCreator(creator);
                        useInventoryUserKnifeInout.setCreatorName(creatorName);
                        useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessTypeDesc());
                        useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnifeInout.setProcessId(list.get(0).getProcessId());
                        useInventoryUserKnifeInout.setRoleId(roleId);
                        useInventoryUserKnifeInout.setRoleName(roleName);
                        useInventoryUserKnifeInout.setDepartmentId(departmentId);
                        useInventoryUserKnifeInout.setDepartmentName(departmentName);
                        useInventoryUserKnifeInout.setChannelCode(channelCode);
//                        useInventoryUserKnifeInout.setCheckInventoryInoutId(checkInventoryInoutId);
                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
                    }


                    if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getLabelCode())) {
//                        UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                        useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                        useInventoryUserKnife.setStorageInventoryUserId(storageInventoryUser.getId());
//                        useInventoryUserKnife.setStorageInventoryInoutId(inventoryInoutId);
//                        useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
//                        UseInventoryUserKnifeInout useInventoryUserKnifeInout=new UseInventoryUserKnifeInout();
//                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
//                        useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
//                        useInventoryUserKnifeInout.setStorageInventoryInoutId(inventoryInoutId);
//                        useInventoryUserKnifeInout.setStorageInventoryUserId(storageInventoryUser.getId());
//                        useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
////                        useInventoryUserKnifeInout.setUseInventoryInoutId()
//                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
                    } else {
//                        List<UseInventoryUserKnife> useInventoryUserKnives=useInventoryUserKnifeService.list(new QueryWrapper<UseInventoryUserKnife>().eq("use_inventory_user_id",useInventoryInoutDetailForm.getId()).eq("status",UseInventoryUserKnife.Status.used.getValue()));
//                        int size=useInventoryUserKnives.size();
//                        if (size>useInventoryInoutDetailForm.getQuantity()){
//                            size=useInventoryInoutDetailForm.getQuantity();
//                        }
//                        for (int i=0;i<size;i++){
//                            UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                            useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                            useInventoryUserKnife.setId(useInventoryUserKnives.get(i).getId());
//                            useInventoryUserKnifeService.updateById(useInventoryUserKnife);
//                        }
                    }

//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    /**
                     }else{

                     //                        if (skuInventoryUserList.get(0).getQuantity()!=null&&skuInventoryUserList.get(0).getQuantity()>0&&!skuInventoryUserList.get(0).getSkuCode().equals(useInventoryInoutDetailForm.getSkuCode())){
                     //                            throw new BusinessException("此货位已经存放了SKU编码:["+skuInventoryUserList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具");
                     //                        }

                     if (!isCheck&&skuInventoryUserList.get(0).getQuantity()!=null&&skuInventoryUserList.get(0).getQuantity()>0&&!skuInventoryUserList.get(0).getBusinessType().name().equals(businessType.name())){
                     throw new BusinessException("此货位已经存放了"+skuInventoryUserList.get(0).getBusinessType().getDesc()+"的刀具,"+"不可以在存放"+businessType.getDesc()+"的刀具");
                     }
                     if (!creator.equals(skuInventoryUserList.get(0).getCreator())){
                     throw new BusinessException("此货位已被他人占用");
                     }

                     skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
                     if (skuInventoryUserList.size()==0){
                     Integer currentQuantity=0;
                     Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                     StorageInventoryUser storageInventoryUser=new StorageInventoryUser();
                     storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                     storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                     storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                     storageInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                     storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                     storageInventoryUser.setCreator(creator);
                     storageInventoryUser.setCreatorName(creatorName);
                     storageInventoryUser.setCompanyId(BaseDataInit.ENTERPRISE_ID);
                     storageInventoryUser.setDeviceCode(deviceCode);
                     inventoryUserService.save(storageInventoryUser);

                     storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                     storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                     storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                     baseMapper.insert(storageInventoryInoutDetail);
                     }else{
                     Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
                     Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                     StorageInventoryUser storageInventoryUser=new StorageInventoryUser();
                     storageInventoryUser.setId(skuInventoryUserList.get(0).getId());
                     //                        storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                     //                        storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                     //                        storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                     storageInventoryUser.setQuantity(newQuantity);
                     //                        if (newQuantity==0){
                     //                            storageInventoryUser.setBusinessType(null);
                     //                        }else{
                     //                            storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                     //                        }

                     inventoryUserService.updateById(storageInventoryUser);

                     storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                     storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                     storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                     baseMapper.insert(storageInventoryInoutDetail);
                     }

                     }*/
                    storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                    quantity=useInventoryInoutDetailForm.getQuantity();
                    if (spaceInventoryList.size() == 0) {
                        Integer currentQuantity = 0;
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setQuantity(newQuantity);
                        storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                        storageInventorySpace.setCompanyId(enterpriseId);
                        storageInventorySpace.setRemark(storageInventorySpace.getBusinessTypeDesc());
                        storageInventorySpace.setEnterpriseCode(enterpriseCode);
                        storageInventorySpace.setChannelCode(channelCode);
                        storageInventorySpace.setMainCabCode(mainCabCode);

                        /**
                         * 默认包装单位 一粒/片
                         */
                        storageInventorySpace.setPackId(useInventoryInoutDetailForm.getPackId());
                        storageInventorySpace.setPackName(useInventoryInoutDetailForm.getPackName());
                        storageInventorySpace.setUnitName(useInventoryInoutDetailForm.getUnitName());
                        storageInventorySpace.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                        storageInventorySpace.setQuantityPack(newQuantity);


                        inventorySpaceService.save(storageInventorySpace);

                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);

                        storageInventoryInoutDetail.setQuantityCurrent(0);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                        storageInventoryInoutDetail.setQuantity(newQuantity);
                        storageInventoryInoutDetail.setQuantityPackCurrent(0);
                        storageInventoryInoutDetail.setQuantityPackAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    } else {
//                        if (spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&!spaceInventoryList.get(0).getSkuCode().equals(useInventoryInoutDetailForm.getSkuCode())){
//                            throw new BusinessException("此货位已经存放了SKU编码:["+spaceInventoryList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具");
//                        }
//
//                        if (!isCheck&&spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&!spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())){
//                            throw new BusinessException("此货位已经存放了"+spaceInventoryList.get(0).getBusinessType().getDesc()+"的刀具,"+"不可以在存放"+businessType.getDesc()+"的刀具");
//                        }
//                        spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
                        /**
                        if (spaceInventoryList.size() == 0) {
                            Integer currentQuantity = 0;
                            Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                            StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                            storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                            storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventorySpace.setQuantity(newQuantity);
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                            storageInventorySpace.setCompanyId(enterpriseId);
                            storageInventorySpace.setRemark(storageInventorySpace.getBusinessTypeDesc());
                            storageInventorySpace.setEnterpriseCode(enterpriseCode);
                            inventorySpaceService.save(storageInventorySpace);

                            storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                            storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                            storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                            baseMapper.insert(storageInventoryInoutDetail);
                        } else {*/
                            Integer currentQuantity = spaceInventoryList.get(0).getQuantity();
                            Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                            StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                            storageInventorySpace.setId(spaceInventoryList.get(0).getId());
//                            storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                            storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
//                            storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventorySpace.setQuantity(newQuantity);
//                        if (newQuantity==0){
//                            storageInventorySpace.setBusinessType(null);
//                        }else{
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
//                        }
                            Integer currentQuantityPack=spaceInventoryList.get(0).getQuantityPack();
                            if (currentQuantityPack==null){
                                currentQuantityPack=0;
                            }
                            storageInventorySpace.setQuantityPack(currentQuantityPack+quantityPack);

                            inventorySpaceService.updateById(storageInventorySpace);

                            storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                            storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                            storageInventoryInoutDetail.setQuantityPackCurrent(currentQuantityPack);
                            storageInventoryInoutDetail.setQuantityPackAfter(storageInventorySpace.getQuantityPack());
//                            storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                            baseMapper.insert(storageInventoryInoutDetail);
//                        }


//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }

                    if (skuSingleInventoryList.size() == 0) {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        storageSingleInventoryProduct.setCompanyId(enterpriseId);
                        storageSingleInventoryProduct.setRemark(storageSingleInventoryProduct.getBusinessTypeDesc());
                        storageSingleInventoryProduct.setEnterpriseCode(enterpriseCode);
                        storageSingleInventoryProduct.setChannelCode(channelCode);
                        storageSingleInventoryProduct.setMainCabCode(mainCabCode);
                        /**
                         * 默认包装单位 一粒/片
                         */
                        storageSingleInventoryProduct.setPackId(useInventoryInoutDetailForm.getPackId());
                        storageSingleInventoryProduct.setPackName(useInventoryInoutDetailForm.getPackName());
                        storageSingleInventoryProduct.setUnitName(useInventoryInoutDetailForm.getUnitName());
                        storageSingleInventoryProduct.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                        storageSingleInventoryProduct.setQuantityPack(useInventoryInoutDetailForm.getQuantity());
                        storageSingleInventoryProduct.setCreator(JwtUtils.getLoginUserId());
                        storageSingleInventoryProduct.setCreatorName(JwtUtils.getLoginUsername());

                        storageSingleInventoryProductService.save(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(0);
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackSingleCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityPackSingleCabAfter(storageSingleInventoryProduct.getQuantityPack());
                    } else {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
//                        storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                        storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
//                        storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
//                        log.info("singleInvnetoryProduct:{}", JSON.toJSONString(storageSingleInventoryProduct));
                        Integer currentQuantityPack=skuSingleInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageSingleInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackSingleCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackSingleCabAfter(currentQuantityPack+quantityPack);
                    }

                    if (skuInventoryList.size() == 0) {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        storageInventoryProduct.setCompanyId(enterpriseId);
                        storageInventoryProduct.setRemark(storageInventoryProduct.getBusinessTypeDesc());
                        storageInventoryProduct.setEnterpriseCode(enterpriseCode);
                        storageInventoryProduct.setChannelCode(channelCode);
                        /**
                         * 默认包装单位 一粒/片
                         */
                        storageInventoryProduct.setPackId(useInventoryInoutDetailForm.getPackId());
                        storageInventoryProduct.setPackName(useInventoryInoutDetailForm.getPackName());
                        storageInventoryProduct.setUnitName(useInventoryInoutDetailForm.getUnitName());
                        storageInventoryProduct.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                        storageInventoryProduct.setQuantityPack(useInventoryInoutDetailForm.getQuantity());

                        inventoryProductService.save(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityPackCabAfter(storageInventoryProduct.getQuantityPack());
                    } else {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
//                        storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        Integer currentQuantityPack=skuInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        inventoryProductService.updateById(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());

                        storageInventoryInoutDetail.setQuantityPackCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackCabAfter(currentQuantityPack+quantityPack);
                    }
                    if (isCheck && StorageInventoryInout.BusinessTypeChecked.temp.equals(businessTypeChecked)) {
                        List<Integer> businessTypes = new ArrayList<>();
                        businessTypes.add(StorageInventorySpace.BusinessType.repair.getValue());
                        businessTypes.add(StorageInventorySpace.BusinessType.recycle.getValue());
                        count = inventorySpaceService.count(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCheckCabCode()).eq("space_code", useInventoryInoutDetailForm.getCheckSpaceCode()).in("business_type", businessTypes));
                        if (count == 0) {
                            StorageInventoryCheck storageInventoryCheck = new StorageInventoryCheck();
                            storageInventoryCheck.setStatus(StorageInventoryCheck.Status.checked);
                            storageInventoryCheckService.update(storageInventoryCheck, new QueryWrapper<StorageInventoryCheck>().eq("cab_code", useInventoryInoutDetailForm.getCheckCabCode()).eq("space_code", useInventoryInoutDetailForm.getCheckSpaceCode()).eq("status", StorageInventoryCheck.Status.created.getValue()));
                        }
                    }
                    storageInventoryInoutDetail.setMainCabCode(mainCabCode);
                    /**
                     * 默认包装单位 一粒/片
                     */
                    storageInventoryInoutDetail.setPackId(useInventoryInoutDetailForm.getPackId());
                    storageInventoryInoutDetail.setPackName(useInventoryInoutDetailForm.getPackName());
                    storageInventoryInoutDetail.setUnitName(useInventoryInoutDetailForm.getUnitName());
                    storageInventoryInoutDetail.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                    storageInventoryInoutDetail.setQuantityPack(useInventoryInoutDetailForm.getQuantity());
                    baseMapper.insert(storageInventoryInoutDetail);
                } else {
                    throw new BusinessException("出入库类型参数异常");
                }

            }
        } else {
            throw new BusinessException("未提交存放刀具数据");
        }
    }

    //private void setDefaultVal(StorageInventorySpace storageInventorySpace){
    //    storageInventorySpace.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    storageInventorySpace.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    storageInventorySpace.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    storageInventorySpace.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    storageInventorySpace.setQuantityPack(storageInventorySpace.getQuantity());
    //}
    //
    //private void setDefaultVal(StorageInventoryProduct storageInventoryProduct){
    //    storageInventoryProduct.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    storageInventoryProduct.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    storageInventoryProduct.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    storageInventoryProduct.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    storageInventoryProduct.setQuantityPack(storageInventoryProduct.getQuantity());
    //}
    //
    //private void setDefaultVal(StorageSingleInventoryProduct storageSingleInventoryProduct){
    //    storageSingleInventoryProduct.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    storageSingleInventoryProduct.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    storageSingleInventoryProduct.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    storageSingleInventoryProduct.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    storageSingleInventoryProduct.setQuantityPack(storageSingleInventoryProduct.getQuantity());
    //}

    //private void setDefaultVal(StorageInventoryUser storageInventoryUser){
    //    storageInventoryUser.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    storageInventoryUser.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    storageInventoryUser.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    storageInventoryUser.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    storageInventoryUser.setQuantityPack(storageInventoryUser.getQuantity());
    //}

    //private void setDefaultVal(StorageInventoryInoutDetail storageInventoryInoutDetail){
    //    storageInventoryInoutDetail.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    storageInventoryInoutDetail.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    storageInventoryInoutDetail.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    storageInventoryInoutDetail.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    storageInventoryInoutDetail.setQuantityPack(storageInventoryInoutDetail.getQuantity());
    //}

    @Transactional
    void saveDetail4NewOut(List<UseInventoryInoutDetailForm> list, Long storageInventoryInoutId, String inOutTypeName, StorageInventoryInout.BusinessType businessType, boolean isCheck, String deviceCode, StorageInventoryInout.BusinessDetailType businessDetailType, Long checkResultId, StorageInventoryInout.BusinessType businessTypeChecked, Long storageInventoryCheckId) {
        List<Cabinet> cabinets=cabinetService.list(new QueryWrapper<Cabinet>().eq("code",list.get(0).getCabCode()));
        String mainCabCode=null;
        if (cabinets.size()>0){
            mainCabCode=cabinets.get(0).getBelongCabinet();
        }
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        Boolean spaceUserShareFlag = systemRuleInfo.getSpaceUserShareFlag();
        Boolean spaceSkuShareFlag = systemRuleInfo.getSpaceSkuShareFlag();
        Boolean spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
        Boolean spaceTempUserShareFlag = systemRuleInfo.getSpaceTempUserShareFlag();
        Boolean spaceTempSkuShareFlag = systemRuleInfo.getSpaceTempSkuShareFlag();
        if (spaceTempSkuShareFlag || spaceTempUserShareFlag) {
//            spaceTempMoreFlag=true;
        }
        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String channelCode=JwtUtils.getChannelCode();
        if (CollectionUtils.isNotEmpty(list)) {
            if (UseInventoryInout.Type.in.name().equals(inOutTypeName) &&
                    !isCheck
                    && (StorageInventoryInout.BusinessType.repair.equals(businessType) || StorageInventoryInout.BusinessType.recycle.equals(businessType))
            ) {
                saveCheckData(list, businessType, storageInventoryInoutId, businessDetailType);
            }
            for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                if (useInventoryInoutDetailForm.getQuantityPackUnit()==null){
                    useInventoryInoutDetailForm.setQuantityPackUnit(1);
                }
                StorageInventoryInoutDetail storageInventoryInoutDetail = new StorageInventoryInoutDetail();
                BeanUtils.copyProperties(useInventoryInoutDetailForm, storageInventoryInoutDetail);
                storageInventoryInoutDetail.setCompanyId(enterpriseId);
                storageInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                storageInventoryInoutDetail.setId(null);
                storageInventoryInoutDetail.setCreator(creator);
                storageInventoryInoutDetail.setCreatorName(creatorName);
                storageInventoryInoutDetail.setOperationType(StorageInventoryInoutDetail.OperationType.jsonCreator(inOutTypeName));
                storageInventoryInoutDetail.setBusinessType(StorageInventoryInoutDetail.BusinessType.jsonCreator(businessType.name()));
                storageInventoryInoutDetail.setInoutId(storageInventoryInoutId);
                storageInventoryInoutDetail.setChannelCode(channelCode);
                storageInventoryInoutDetail.setMainCabCode(mainCabCode);
//                storageInventoryInoutDetail.setQuantityPack(useInventoryInoutDetailForm.getQuantityPackUnit()*useInventoryInoutDetailForm.getQuantity());

//                Integer quantityPack=storageInventoryInoutDetail.getQuantityPack();
//                Integer quantityPackUnit=useInventoryInoutDetailForm.getQuantityPackUnit();
//                useInventoryInoutDetailForm.setQuantityPack(quantityPack);
//                useInventoryInoutDetailForm.setQuantityPackUnit(quantityPackUnit);
                List<ProductDetail> productDetails = productDetailService.listBySkuCode(useInventoryInoutDetailForm.getSkuCode());
                Integer quantityPack=null;
                Integer quantityPackUnit=null;

//                List<StorageInventorySpace> spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("business_type",businessType.getValue()));
//                List<StorageInventorySpace> spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
                List<CabinetCargoSpace> cabinetCargoSpaces = cargoSpaceService.list(new QueryWrapper<CabinetCargoSpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("code", useInventoryInoutDetailForm.getSpaceCode()));
                if (cabinetCargoSpaces.size() == 0) {
                    throw new BusinessException("未找到库位");
                }
//                if (CabinetCargoSpace.SpaceNature.personal.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
//                    if (!creator.equals(cabinetCargoSpaces.get(0).getPrincipal())){
//                        throw new BusinessException("柜子编号["+cabinetCargoSpaces.get(0).getCode()+"]为用户的专人存贮,其他用户不能打开");
//                    }
//                }
                List<StorageInventorySpace> spaceInventoryList = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                if (UseInventoryInout.Type.out.name().equals(inOutTypeName)&&spaceInventoryList.get(0).getQuantityPackUnit()!=null){
                    useInventoryInoutDetailForm.setQuantityPackUnit(spaceInventoryList.get(0).getQuantityPackUnit());
                }
                if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
                    /**
                     if (CabinetCargoSpace.SpaceNature.common.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     if (StorageInventoryInout.BusinessType.temp.equals(businessType)&&spaceInventoryList.size()!=0&&spaceInventoryList.get(0).getQuantity()>0){
                     throw new BusinessException("请选择空的库位");
                     }
                     }else if(CabinetCargoSpace.SpaceNature.personal.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     if (!creator.equals(cabinetCargoSpaces.get(0).getPrincipal())){
                     throw new BusinessException("柜子编号["+cabinetCargoSpaces.get(0).getCode()+"]为用户的专人存贮,其他用户不能打开");
                     }

                     }else if(CabinetCargoSpace.SpaceNature.specialClass.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     Map paramMap=new HashMap();
                     paramMap.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
                     List<ProductDetailVO> productDetailVOS=productDetailService.list4app(paramMap);
                     if (productDetailVOS.size()==0){
                     throw new BusinessException("未找到产品");
                     }
                     if (cabinetCargoSpaces.get(0).getSpaceProductType()!=null&&!cabinetCargoSpaces.get(0).getSpaceProductType().equals(productDetailVOS.get(0).getProductTypeId())){
                     throw new BusinessException("此库位不能存储此产品类型["+productDetailVOS.get(0).getProductTypeName()+"]");
                     }
                     }else if(CabinetCargoSpace.SpaceNature.repair.equals(cabinetCargoSpaces.get(0).getSpaceNature())) {

                     }else if(CabinetCargoSpace.SpaceNature.recycle.equals(cabinetCargoSpaces.get(0).getSpaceNature())) {

                     }else{
                     throw new BusinessException("请先设置货道存贮性质");
                     }

                     if (spaceInventoryList.size()>0&&!spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())){
                     throw new BusinessException("此库位之前存贮的是["+spaceInventoryList.get(0).getBusinessType().getDesc()+"],不能再存贮["+businessType.getDesc()+"]");
                     }
                     if (spaceInventoryList.size()>0){
                     Integer sum=getSumQuantityBySpace(spaceInventoryList);
                     if (sum>=cabinetCargoSpaces.get(0).getQuantity()){
                     throw new BusinessException("柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]库位["+useInventoryInoutDetailForm.getSpaceCode()+"]已经存满");
                     }
                     }
                     List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));
                     if (skuInventoryUserList.size()>0&&!creator.equals(skuInventoryUserList.get(0).getCreator())){
                     throw new BusinessException("此库位已被他人占用");
                     }*/
                    /**
                     if (StorageInventoryInout.BusinessType.temp.equals(businessType)&&spaceInventoryList.size()!=0&&spaceInventoryList.get(0).getQuantity()>0){
                     throw new BusinessException("请选择空的库位");
                     }
                     if(CabinetCargoSpace.SpaceNature.personal.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
                     if (!creator.equals(cabinetCargoSpaces.get(0).getPrincipal())){
                     throw new BusinessException("柜子编号["+cabinetCargoSpaces.get(0).getCode()+"]为用户的专人存贮,其他用户不能打开");
                     }

                     }
                     if (cabinetCargoSpaces.get(0).getSpaceProductType()!=null){
                     Map paramMap=new HashMap();
                     paramMap.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
                     List<ProductDetailVO> productDetailVOS=productDetailService.list4app(paramMap);
                     if (productDetailVOS.size()==0){
                     throw new BusinessException("未找到产品");
                     }
                     if(!cabinetCargoSpaces.get(0).getSpaceProductType().equals(productDetailVOS.get(0).getProductTypeId())){
                     throw new BusinessException("此库位不能存储此产品类型["+productDetailVOS.get(0).getProductTypeName()+"]");
                     }

                     }
                     if (spaceInventoryList.size()>0&&!spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())){
                     throw new BusinessException("此库位之前存贮的是["+spaceInventoryList.get(0).getBusinessType().getDesc()+"],不能再存贮["+businessType.getDesc()+"]");
                     }
                     if (spaceInventoryList.size()>0){
                     Integer sum=getSumQuantityBySpace(spaceInventoryList);
                     if (sum>=cabinetCargoSpaces.get(0).getQuantity()){
                     throw new BusinessException("柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]库位["+useInventoryInoutDetailForm.getSpaceCode()+"]已经存满");
                     }
                     }
                     List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));
                     if (skuInventoryUserList.size()>0&&!creator.equals(skuInventoryUserList.get(0).getCreator())){
                     throw new BusinessException("此库位已被他人占用");
                     }*/
                    log.info("{}", StorageInventoryInout.BusinessType.temp.equals(businessType));
                    if (cabinetCargoSpaces.get(0).getSpaceType() != null &&
                            (CabinetCargoSpace.SpaceType.common.equals(cabinetCargoSpaces.get(0).getSpaceType()) ||
                                    CabinetCargoSpace.SpaceType.temp.equals(cabinetCargoSpaces.get(0).getSpaceType())) &&
                            (StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()))

                    ) {
                        int count = storageInventoryKnifeService.count(new QueryWrapper<StorageInventoryKnife>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                        if (!spaceTempMoreFlag&&StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()) && StorageInventoryInout.BusinessType.temp.equals(businessType) && count > 0) {
                            throw new BusinessException("请选择空的库位或者设置暂存允许多存");
                        }
                    }

                    log.info("{},{}", creator, cabinetCargoSpaces.get(0).getPrincipal());
                    if (StringUtils.isNotBlank(cabinetCargoSpaces.get(0).getPrincipal())) {
                        if (!(","+cabinetCargoSpaces.get(0).getPrincipal()+",").contains(","+creator+",")) {
                            throw new BusinessException("柜子编号[" + cabinetCargoSpaces.get(0).getCode() + "]为用户的专人存贮,其他用户不能打开");
                        }

                    }
                    if (StringUtils.isNotBlank(cabinetCargoSpaces.get(0).getSkuCode())) {
                        if (!useInventoryInoutDetailForm.getSkuCode().equals(cabinetCargoSpaces.get(0).getSkuCode())) {
                            throw new BusinessException("此库位不能存储此产品SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]的产品");
                        }
                    }
                    if (cabinetCargoSpaces.get(0).getSpaceProductType() != null && cabinetCargoSpaces.get(0).getSpaceProductType() != 0) {
                        Map paramMap = new HashMap();
                        paramMap.put("skuCode4app", useInventoryInoutDetailForm.getSkuCode());
                        List<ProductDetailVO> productDetailVOS = productDetailService.list4app(paramMap);
                        if (productDetailVOS.size() == 0) {
                            throw new BusinessException("未找到产品");
                        }
                        if (!cabinetCargoSpaces.get(0).getSpaceProductType().equals(productDetailVOS.get(0).getProductTypeId())) {
                            throw new BusinessException("此库位不能存储此产品类型[" + productDetailVOS.get(0).getProductTypeName() + "]");
                        }

                    }
                    if (cabinetCargoSpaces.get(0).getSpaceType() != null && !CabinetCargoSpace.SpaceType.common.equals(cabinetCargoSpaces.get(0).getSpaceType())) {
                        if (!cabinetCargoSpaces.get(0).getSpaceType().name().equals(businessType.name())
                        ) {
                            throw new BusinessException("此库位只能存贮[" + cabinetCargoSpaces.get(0).getSpaceType().getDesc() + "],不能再存贮[" + businessType.getDesc() + "]");
                        }
                    }
                    if (spaceInventoryList.size() > 0 && !spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())) {
                        throw new BusinessException("此库位之前存贮的是[" + spaceInventoryList.get(0).getBusinessType().getDesc() + "],不能再存贮[" + businessType.getDesc() + "]");
                    }
                    if (spaceInventoryList.size() > 0) {
                        Integer sum = getSumQuantityBySpace(spaceInventoryList);
                        sum += useInventoryInoutDetailForm.getQuantity();
                        if (sum > cabinetCargoSpaces.get(0).getQuantity()) {
                            throw new BusinessException("柜子编号[" + useInventoryInoutDetailForm.getCabCode() + "]库位[" + useInventoryInoutDetailForm.getSpaceCode() + "]已经存满");
                        }
                    }
                    /**
                    List<StorageInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                    if (((!spaceUserShareFlag && !StorageInventoryInout.BusinessType.temp.equals(businessType)) ||
                            (!spaceTempUserShareFlag && StorageInventoryInout.BusinessType.temp.equals(businessType)))
                            && skuInventoryUserList.size() > 0 && !creator.equals(skuInventoryUserList.get(0).getCreator())) {
                        throw new BusinessException("此库位已被他人占用");
                    }*/
                    log.info("{}", StorageInventoryInout.BusinessType.temp.equals(businessType));
                    if (cabinetCargoSpaces.get(0).getSpaceType() != null &&
                            (CabinetCargoSpace.SpaceType.common.equals(cabinetCargoSpaces.get(0).getSpaceType()) ||
                                    CabinetCargoSpace.SpaceType.temp.equals(cabinetCargoSpaces.get(0).getSpaceType())) &&
                            (StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()))

                    ) {
                        int count = storageInventoryKnifeService.count(new QueryWrapper<StorageInventoryKnife>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                        if (!spaceTempMoreFlag&&StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()) && StorageInventoryInout.BusinessType.temp.equals(businessType) && count > 0) {
                            throw new BusinessException("请选择空的库位或者设置暂存允许多存");
                        }
                    }

                    log.info("{},{}", creator, cabinetCargoSpaces.get(0).getPrincipal());
                    if (StringUtils.isNotBlank(cabinetCargoSpaces.get(0).getPrincipal())) {
                        if (!(","+cabinetCargoSpaces.get(0).getPrincipal()+",").contains(","+creator+",")) {
                            throw new BusinessException("柜子编号[" + cabinetCargoSpaces.get(0).getCode() + "]为用户的专人存贮,其他用户不能打开");
                        }

                    }
                }

                List<StorageInventoryProduct> skuInventoryList = inventoryProductService.list(new QueryWrapper<StorageInventoryProduct>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("business_type", businessType.getValue()).eq("enterprise_code", enterpriseCode).eq("quantity_pack_unit",useInventoryInoutDetailForm.getQuantityPackUnit()));
                List<StorageSingleInventoryProduct> skuSingleInventoryList = storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("business_type", businessType.getValue()).eq("quantity_pack_unit",useInventoryInoutDetailForm.getQuantityPackUnit()));

                spaceInventoryList = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                if (UseInventoryInout.Type.out.name().equals(inOutTypeName)) {
//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }
//                    if (skuSingleInventoryList.size()==0){
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]上的SKU["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }

//                    spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));

//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("creator",useInventoryInoutDetailForm.getCreator()));
//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));
//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));
//                    List<StorageInventoryKnife> skuInventoryKnifeList = storageInventoryKnifeService.list(new QueryWrapper<StorageInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));

                    if (spaceInventoryList.size() == 0) {
                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(), "未找到柜子编号[" + useInventoryInoutDetailForm.getCabCode() + "]库位[" + useInventoryInoutDetailForm.getSpaceCode() + "]上的SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]刀具产品数据");
                    } else {

//                        useInventoryInoutDetailForm.setRemainingTime(skuInventoryKnifeList.get(0).getRemainingTime());
//                        useInventoryInoutDetailForm.setLifeUnit(skuInventoryKnifeList.get(0).getLifeUnit());
//                        useInventoryInoutDetailForm.setSettingTime(skuInventoryKnifeList.get(0).getSettingTime());

//                        if (StringUtils.isBlank(deviceCode)) {
//                            deviceCode = skuInventoryKnifeList.get(0).getDeviceCode();
//                            useInventoryInoutDetailForm.setDeviceCode(deviceCode);
//                        }
//                        List<StorageInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id", skuInventoryKnifeList.get(0).getStorageInventoryUserId()));
//                        if (skuInventoryUserList.size() == 0) {
//                            throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]库位["+useInventoryInoutDetailForm.getSpaceCode()+"]上的SKU编号["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                        }
//                        storageInventoryKnifeService.remove(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));


                        Integer quantity = useInventoryInoutDetailForm.getQuantity();
                        if (quantity <= 0) {
                            throw new BusinessException("领取数量异常");
                        }
                        if (quantity > 0) {
                            quantity = -1 * quantity;
                        }


                        /**
                        if (skuInventoryUserList.size() > 0) {
                            if (StringUtils.isBlank(deviceCode)) {
                                deviceCode = skuInventoryUserList.get(0).getDeviceCode();
                                useInventoryInoutDetailForm.setDeviceCode(deviceCode);
                            }
                            Integer currentQuantity = skuInventoryUserList.get(0).getQuantity();
                            Integer newQuantity = currentQuantity + quantity;
                            if (newQuantity < 0) {
//                                throw new BusinessException("SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品库存不足");
                            }

                            StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                            storageInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                        storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
//                        storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventoryUser.setQuantity(newQuantity);
                            if (newQuantity <= 0) {
                                storageInventoryUser.setBusinessType(null);
//                            storageInventoryUser.setSkuCode(null);
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            } else {
//                            storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                                inventoryUserService.updateById(storageInventoryUser);
                            }
                            if (spaceInventoryList.size() > 0) {
                                storageInventoryInoutDetail.setQuantityCurrent(spaceInventoryList.get(0).getQuantity());
                                storageInventoryInoutDetail.setQuantityAfter(spaceInventoryList.get(0).getQuantity() + quantity);
                            } else {
                                storageInventoryInoutDetail.setQuantityCurrent(skuInventoryList.get(0).getQuantity());
                                storageInventoryInoutDetail.setQuantityAfter(skuInventoryList.get(0).getQuantity() + quantity);
                            }
                        }*/
                        /**
                        if (spaceInventoryList.size() > 0) {
                            storageInventoryInoutDetail.setQuantityCurrent(spaceInventoryList.get(0).getQuantity());
                            storageInventoryInoutDetail.setQuantityAfter(spaceInventoryList.get(0).getQuantity() + quantity);
                        } else {
                            storageInventoryInoutDetail.setQuantityCurrent(skuInventoryList.get(0).getQuantity());
                            storageInventoryInoutDetail.setQuantityAfter(skuInventoryList.get(0).getQuantity() + quantity);
                        }*/
                        useInventoryInoutDetailForm.setQuantityCurrent(storageInventoryInoutDetail.getQuantityCurrent());
                        useInventoryInoutDetailForm.setQuantityAfter(storageInventoryInoutDetail.getQuantityAfter());

                        storageInventoryInoutDetail.setQuantity(quantity);
                        storageInventoryInoutDetail.setCreator(useInventoryInoutDetailForm.getCreator());
                        storageInventoryInoutDetail.setCreatorName(useInventoryInoutDetailForm.getCreatorName());
                        storageInventoryInoutDetail.setModifier(creator);
                        storageInventoryInoutDetail.setModifierName(creatorName);



//                        baseMapper.insert(storageInventoryInoutDetail);
//                        useInventoryInoutDetailForm.setStorageInventoryInoutDetailId(storageInventoryInoutDetail.getId());
//                        useInventoryInoutDetailForm.setLabelCode(skuInventoryUserList.get(0).getLabelCode());
//                        if (StringUtils.isNotBlank(skuInventoryUserList.get(0).getLabelCode())){
//                            UseInventoryUserKnifeInout useInventoryUserKnifeInout=new UseInventoryUserKnifeInout();
//                            useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
//                            useInventoryUserKnifeInout.setCode(skuInventoryUserList.get(0).getLabelCode());
//                            useInventoryUserKnifeInout.setStorageInventoryInoutId(inventoryInoutId);
//                            useInventoryUserKnifeInout.setStorageInventoryUserId(storageInventoryUser.getId());
//                            useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
////                        useInventoryUserKnifeInout.setUseInventoryInoutId()
//                            useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
//                        }
                    }
                    if (spaceInventoryList.get(0).getQuantityPackUnit()!=null){
                        useInventoryInoutDetailForm.setQuantityPackUnit(spaceInventoryList.get(0).getQuantityPackUnit());
                    }



                    quantityPack=useInventoryInoutDetailForm.getQuantityPackUnit()*useInventoryInoutDetailForm.getQuantity();
                    quantityPackUnit=useInventoryInoutDetailForm.getQuantityPackUnit();

                    storageInventoryInoutDetail.setPackName(spaceInventoryList.get(0).getPackName());
                    storageInventoryInoutDetail.setPackId(spaceInventoryList.get(0).getPackId());
                    storageInventoryInoutDetail.setUnitName(spaceInventoryList.get(0).getUnitName());
                    useInventoryInoutDetailForm.setQuantityPack(quantityPack);
                    useInventoryInoutDetailForm.setQuantityPackUnit(storageInventoryInoutDetail.getQuantityPackUnit());
                    useInventoryInoutDetailForm.setPackName(storageInventoryInoutDetail.getPackName());
                    useInventoryInoutDetailForm.setPackId(storageInventoryInoutDetail.getPackId());
                    useInventoryInoutDetailForm.setUnitName(storageInventoryInoutDetail.getUnitName());

                    Integer quantity = useInventoryInoutDetailForm.getQuantity();
                    if (quantity <= 0) {
                        throw new BusinessException("取数量参数异常");
                    }
                    if (quantity > 0) {
                        quantity = -1 * quantity;
                    }
                    if(quantityPack>0){
                        quantityPack=-1*quantityPack;
                    }
                    if (spaceInventoryList.size() > 0) {
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]货道["+useInventoryInoutDetailForm.getSpaceCode()+"]上的SKU编号["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }else{


                        Integer currentQuantity = spaceInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                            throw new BusinessException("SKU编号["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品库存不足");
                        }

                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setId(spaceInventoryList.get(0).getId());
//                        storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                        storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
//                        storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setQuantity(newQuantity);

                        Integer currentQuantityPack=spaceInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventorySpace.setQuantityPack(currentQuantityPack+quantityPack);
                        storageInventorySpace.setQuantityPackUnit(quantityPackUnit);

                        if (newQuantity <= 0) {
                            storageInventorySpace.setBusinessType(null);
                            storageInventorySpace.setQuantity(0);
                            storageInventorySpace.setQuantityPack(0);
//                            storageInventorySpace.setSkuCode(null);
//                            inventorySpaceService.removeById(spaceInventoryList.get(0).getId());
                        }
//                        else {
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                            inventorySpaceService.updateById(storageInventorySpace);
//                        }
                        storageInventoryInoutDetail.setQuantityCurrent(spaceInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityAfter(storageInventorySpace.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackAfter(currentQuantityPack+quantityPack);

                        useInventoryInoutDetailForm.setQuantityCurrent(storageInventoryInoutDetail.getQuantityCurrent());
                        useInventoryInoutDetailForm.setQuantityAfter(storageInventoryInoutDetail.getQuantityAfter());
                        useInventoryInoutDetailForm.setQuantityPackCurrent(storageInventoryInoutDetail.getQuantityPackCurrent());
                        useInventoryInoutDetailForm.setQuantityPackAfter(storageInventoryInoutDetail.getQuantityPackAfter());
                        /**
                        if (skuSingleInventoryList.size() > 0) {
                            StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                            storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
//                            storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                            storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + quantity);
                            if (storageSingleInventoryProduct.getQuantity() <= 0) {
                                storageSingleInventoryProduct.setBusinessType(null);
//                            storageSingleInventoryProduct.setSkuCode(null);
                                storageSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                            } else {
//                                storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                                storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);
                            }
                        }

                        if (skuInventoryList.size() > 0) {
                            StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                            storageInventoryProduct.setId(skuInventoryList.get(0).getId());
//                            storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + quantity);
                            if (storageInventoryProduct.getQuantity() <= 0) {
                                storageInventoryProduct.setBusinessType(null);
//                            storageInventoryProduct.setSkuCode(null);
                                inventoryProductService.removeById(skuInventoryList.get(0).getId());
                            } else {
//                                storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                                inventoryProductService.updateById(storageInventoryProduct);
                            }
                        }*/
//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }
                    if (skuSingleInventoryList.size() > 0) {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
//                            storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                            storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + quantity);
                        Integer currentQuantityPack=skuSingleInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageSingleInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        if (storageSingleInventoryProduct.getQuantity() <= 0) {
                            storageSingleInventoryProduct.setBusinessType(null);
                            storageSingleInventoryProduct.setQuantity(0);
                            storageSingleInventoryProduct.setQuantityPack(0);
//                            storageSingleInventoryProduct.setSkuCode(null);
//                            storageSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                        }
//                        else {
//                                storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                            storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);
//                        }

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackSingleCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackSingleCabAfter(storageSingleInventoryProduct.getQuantityPack());
                        useInventoryInoutDetailForm.setQuantitySingleCabCurrent(storageInventoryInoutDetail.getQuantitySingleCabCurrent());
                        useInventoryInoutDetailForm.setQuantitySingleCabAfter(storageInventoryInoutDetail.getQuantitySingleCabAfter());
                        useInventoryInoutDetailForm.setQuantityPackSingleCabCurrent(storageInventoryInoutDetail.getQuantityPackSingleCabCurrent());
                        useInventoryInoutDetailForm.setQuantityPackSingleCabAfter(storageInventoryInoutDetail.getQuantityPackSingleCabAfter());
                    }

                    if (skuInventoryList.size() > 0) {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setId(skuInventoryList.get(0).getId());
//                            storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + quantity);
                        //                        if (quantityPack!=null){
                        Integer currentQuantityPack=skuInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
//                            cellInventorySpace.setQuantityPackUnit(quantityPackUnit);
//                        }
                        if (storageInventoryProduct.getQuantity() <= 0) {
                            storageInventoryProduct.setBusinessType(null);
//                            storageInventoryProduct.setSkuCode(null);
//                            inventoryProductService.removeById(skuInventoryList.get(0).getId());
                            storageInventoryProduct.setQuantity(0);
                            storageInventoryProduct.setQuantityPack(0);
                        }
//                        else{
//                                storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                            inventoryProductService.updateById(storageInventoryProduct);
//                        }

                        storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackCabAfter(storageInventoryProduct.getQuantityPack());
                        useInventoryInoutDetailForm.setQuantityCabCurrent(storageInventoryInoutDetail.getQuantityCabCurrent());
                        useInventoryInoutDetailForm.setQuantityCabAfter(storageInventoryInoutDetail.getQuantityCabAfter());
                        useInventoryInoutDetailForm.setQuantityPackCabCurrent(storageInventoryInoutDetail.getQuantityPackCabCurrent());
                        useInventoryInoutDetailForm.setQuantityPackCabAfter(storageInventoryInoutDetail.getQuantityPackCabAfter());

                    }
                    BigDecimal price=null;
                    BigDecimal total=null;
                    if (productDetails.size()>0&&productDetails.get(0).getMarketPrice()!=null){
//                    quantityPackUnit=productDetails.get(0).getUnitRate();
//                    if (quantityPackUnit!=null){
//                        quantityPack=cellInventoryInoutDetailForm.getQuantity()*quantityPackUnit;
//                    }
//                    packId=productDetails.get(0).getPackId();
                        price=productDetails.get(0).getMarketPrice();
                        if (price!=null){
                            total=price.multiply(BigDecimal.valueOf(Math.abs(quantityPack)));
                        }
                    }
                    storageInventoryInoutDetail.setPrice(price);
                    storageInventoryInoutDetail.setTotal(total);
                    storageInventoryInoutDetail.setQuantityPack(quantityPack);
                    storageInventoryInoutDetail.setQuantityPackUnit(quantityPackUnit);
                    useInventoryInoutDetailForm.setPrice(price);
                    useInventoryInoutDetailForm.setTotal(total);
                    useInventoryInoutDetailForm.setQuantityPack(quantityPack);
                    useInventoryInoutDetailForm.setQuantityPackUnit(quantityPackUnit);
                    baseMapper.insert(storageInventoryInoutDetail);
                    useInventoryInoutDetailForm.setStorageInventoryInoutDetailId(storageInventoryInoutDetail.getId());
                } else if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
                    if (!isCheck && (systemRuleInfo != null && systemRuleInfo.getAbFlag() != null && !systemRuleInfo.getAbFlag())) {
                        if (!creator.equals(useInventoryInoutDetailForm.getCreator())) {
                            throw new BusinessException("系统设置不允许A借B还");
                        }
                    }

//                    Integer quantity=useInventoryInoutDetailForm.getQuantity();
                    if (useInventoryInoutDetailForm.getQuantity() <= 0) {
                        throw new BusinessException("存数量参数异常");
                    }
                    quantityPack=useInventoryInoutDetailForm.getQuantityPackUnit()*useInventoryInoutDetailForm.getQuantity();
                    quantityPackUnit=useInventoryInoutDetailForm.getQuantityPackUnit();

//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("creator",creator));
//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()));

//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));

//                    if (skuInventoryUserList.size()==0){
//                        Integer currentQuantity=0;
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                    StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                    storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    storageInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                    storageInventoryUser.setCreator(creator);
                    storageInventoryUser.setCreatorName(creatorName);
                    storageInventoryUser.setCompanyId(enterpriseId);
                    storageInventoryUser.setDeviceCode(deviceCode);
                    storageInventoryUser.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                    storageInventoryUser.setRemark(storageInventoryUser.getBusinessTypeDesc());
                    storageInventoryUser.setWorkOrderId(list.get(0).getWorkOrderId());
                    storageInventoryUser.setProcessId(list.get(0).getProcessId());
                    storageInventoryUser.setEnterpriseCode(enterpriseCode);
                    storageInventoryUser.setChannelCode(channelCode);
                    inventoryUserService.save(storageInventoryUser);

                    storageInventoryInoutDetail.setQuantityUserCurrent(0);
                    storageInventoryInoutDetail.setQuantityAfter(useInventoryInoutDetailForm.getQuantity());
                    storageInventoryInoutDetail.setStorageInventoryUserId(storageInventoryUser.getId());

                    int count = storageInventoryKnifeService.count(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                    log.info("storage inventory knife count:{}", count);
                    if (count > 0) {
                        storageInventoryKnifeService.remove(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                    }

                    StorageInventoryKnife storageInventoryKnife = new StorageInventoryKnife();
                    storageInventoryKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    storageInventoryKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    storageInventoryKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    storageInventoryKnife.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    storageInventoryKnife.setBusinessType(StorageInventoryKnife.BusinessType.jsonCreator(businessType.name()));
                    storageInventoryKnife.setCreator(creator);
                    storageInventoryKnife.setCreatorName(creatorName);
                    storageInventoryKnife.setCompanyId(enterpriseId);
                    storageInventoryKnife.setDeviceCode(deviceCode);
                    storageInventoryKnife.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                    storageInventoryKnife.setStorageInventoryUserId(storageInventoryUser.getId());

                    storageInventoryKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                    storageInventoryKnife.setProcessId(list.get(0).getProcessId());
                    storageInventoryKnife.setEnterpriseCode(enterpriseCode);
                    storageInventoryKnife.setBusinessDetailType(StorageInventoryKnife.BusinessDetailType.jsonCreator(businessDetailType.name()));
                    storageInventoryKnife.setRemark(storageInventoryKnife.getBusinessDetailTypeDesc());
                    storageInventoryKnife.setCategoryId(useInventoryInoutDetailForm.getCategoryId());
                    storageInventoryKnife.setChannelCode(channelCode);
                    if (!isCheck) {
                        List<UseInventoryKnife> useInventoryKnives = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                        if (useInventoryKnives.size() == 0) {
//                            throw new BusinessException("未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
                        }
                        if (useInventoryKnives.size() > 0) {
                            if (useInventoryKnives.get(0).getSettingTime() != null) {
                                if (useInventoryKnives.get(0).getLifeUnit() != null) {
                                    storageInventoryKnife.setLifeUnit(StorageInventoryKnife.LifeUnit.jsonCreator(useInventoryKnives.get(0).getLifeUnit().name()));
                                }
                                storageInventoryKnife.setSettingTime(useInventoryKnives.get(0).getSettingTime());
                                storageInventoryKnife.setRemainingTime(useInventoryKnives.get(0).getRemainingTime());
                            } else {
//                                List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                                if (productDetails.size() > 0) {
                                    if (productDetails.get(0).getLifeSpan() != null) {
//                                        useInventoryUserKnife.setInitTime(productDetails.get(0).getLifeSpan());
//                                        useInventoryUserKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                        storageInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                        storageInventoryKnife.setSettingTime(productDetails.get(0).getLifeSpan());

//                                        useInventoryUserKnifeInout.setInitTime(productDetails.get(0).getLifeSpan());
//                                        useInventoryUserKnifeInout.setRemainingTime(productDetails.get(0).getLifeSpan());
                                    }

                                    if (productDetails.get(0).getLifeUnit() != null) {
                                        storageInventoryKnife.setLifeUnit(StorageInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
//                                        useInventoryUserKnife.setLifeUnit(UseInventoryUserKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
//                                        useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                    }

                                }
                            }

                        }

                    } else {
                        storageInventoryKnife.setSettingTime(useInventoryInoutDetailForm.getSettingTime());
                        storageInventoryKnife.setRemainingTime(useInventoryInoutDetailForm.getRemainingTime());
                        storageInventoryKnife.setLifeUnit(useInventoryInoutDetailForm.getLifeUnit());
                    }


                    storageInventoryKnifeService.save(storageInventoryKnife);

                    if (isCheck) {


                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                        useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        if (StringUtils.isNotBlank(list.get(0).getRemark())){
                            useInventoryUserKnife.setRemark(list.get(0).getRemark());
                        }else{
                            useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                        }

                        useInventoryUserKnifeService.update(useInventoryUserKnife, new QueryWrapper<UseInventoryUserKnife>().eq("code", useInventoryInoutDetailForm.getLabelCode()));

//                        List<StorageInventoryCheck> storageInventoryChecks=storageInventoryCheckService.list(new QueryWrapper<StorageInventoryCheck>().eq("cab_code",isCheck?useInventoryInoutDetailForm.getCheckCabCode():useInventoryInoutDetailForm.getCabCode()).eq("space_code",isCheck?useInventoryInoutDetailForm.getCheckSpaceCode():useInventoryInoutDetailForm.getSpaceCode()).eq("status",StorageInventoryCheck.Status.created.getValue()));
                        UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();
                        useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
                        useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUserKnifeInout.setStorageInventoryUserId(storageInventoryUser.getId());
                        useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
                        useInventoryUserKnifeInout.setCheckResultId(checkResultId);
//                        useInventoryUserKnifeInout.setStorageInventoryCheckId(storageInventoryChecks.get(0).getId());
                        useInventoryUserKnifeInout.setStorageInventoryCheckId(storageInventoryCheckId);
//                        useInventoryUserKnifeInout.setCellInventoryInoutId(cellInventoryInoutId);
//                        useInventoryUserKnifeInout.setDeviceCode(deviceCode);
                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
                        useInventoryUserKnifeInout.setCreator(creator);
                        useInventoryUserKnifeInout.setCreatorName(creatorName);
                        useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessTypeDesc());
                        useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnifeInout.setProcessId(list.get(0).getProcessId());
                        useInventoryUserKnifeInout.setChannelCode(channelCode);
//                        useInventoryUserKnifeInout.setCheckInventoryInoutId(checkInventoryInoutId);
                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
                    }


                    if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getLabelCode())) {
//                        UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                        useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                        useInventoryUserKnife.setStorageInventoryUserId(storageInventoryUser.getId());
//                        useInventoryUserKnife.setStorageInventoryInoutId(inventoryInoutId);
//                        useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
//                        UseInventoryUserKnifeInout useInventoryUserKnifeInout=new UseInventoryUserKnifeInout();
//                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
//                        useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
//                        useInventoryUserKnifeInout.setStorageInventoryInoutId(inventoryInoutId);
//                        useInventoryUserKnifeInout.setStorageInventoryUserId(storageInventoryUser.getId());
//                        useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
////                        useInventoryUserKnifeInout.setUseInventoryInoutId()
//                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
                    } else {
//                        List<UseInventoryUserKnife> useInventoryUserKnives=useInventoryUserKnifeService.list(new QueryWrapper<UseInventoryUserKnife>().eq("use_inventory_user_id",useInventoryInoutDetailForm.getId()).eq("status",UseInventoryUserKnife.Status.used.getValue()));
//                        int size=useInventoryUserKnives.size();
//                        if (size>useInventoryInoutDetailForm.getQuantity()){
//                            size=useInventoryInoutDetailForm.getQuantity();
//                        }
//                        for (int i=0;i<size;i++){
//                            UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                            useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                            useInventoryUserKnife.setId(useInventoryUserKnives.get(i).getId());
//                            useInventoryUserKnifeService.updateById(useInventoryUserKnife);
//                        }
                    }

//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    /**
                     }else{

                     //                        if (skuInventoryUserList.get(0).getQuantity()!=null&&skuInventoryUserList.get(0).getQuantity()>0&&!skuInventoryUserList.get(0).getSkuCode().equals(useInventoryInoutDetailForm.getSkuCode())){
                     //                            throw new BusinessException("此货位已经存放了SKU编码:["+skuInventoryUserList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具");
                     //                        }

                     if (!isCheck&&skuInventoryUserList.get(0).getQuantity()!=null&&skuInventoryUserList.get(0).getQuantity()>0&&!skuInventoryUserList.get(0).getBusinessType().name().equals(businessType.name())){
                     throw new BusinessException("此货位已经存放了"+skuInventoryUserList.get(0).getBusinessType().getDesc()+"的刀具,"+"不可以在存放"+businessType.getDesc()+"的刀具");
                     }
                     if (!creator.equals(skuInventoryUserList.get(0).getCreator())){
                     throw new BusinessException("此货位已被他人占用");
                     }

                     skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
                     if (skuInventoryUserList.size()==0){
                     Integer currentQuantity=0;
                     Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                     StorageInventoryUser storageInventoryUser=new StorageInventoryUser();
                     storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                     storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                     storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                     storageInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                     storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                     storageInventoryUser.setCreator(creator);
                     storageInventoryUser.setCreatorName(creatorName);
                     storageInventoryUser.setCompanyId(BaseDataInit.ENTERPRISE_ID);
                     storageInventoryUser.setDeviceCode(deviceCode);
                     inventoryUserService.save(storageInventoryUser);

                     storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                     storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                     storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                     baseMapper.insert(storageInventoryInoutDetail);
                     }else{
                     Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
                     Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                     StorageInventoryUser storageInventoryUser=new StorageInventoryUser();
                     storageInventoryUser.setId(skuInventoryUserList.get(0).getId());
                     //                        storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                     //                        storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                     //                        storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                     storageInventoryUser.setQuantity(newQuantity);
                     //                        if (newQuantity==0){
                     //                            storageInventoryUser.setBusinessType(null);
                     //                        }else{
                     //                            storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                     //                        }

                     inventoryUserService.updateById(storageInventoryUser);

                     storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                     storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                     storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                     baseMapper.insert(storageInventoryInoutDetail);
                     }

                     }*/
//                    quantity=useInventoryInoutDetailForm.getQuantity();
                    storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    if (spaceInventoryList.size() == 0) {
                        Integer currentQuantity = 0;
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setQuantity(newQuantity);
                        storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                        storageInventorySpace.setCompanyId(enterpriseId);
                        storageInventorySpace.setRemark(storageInventorySpace.getBusinessTypeDesc());
                        storageInventorySpace.setEnterpriseCode(enterpriseCode);
                        storageInventorySpace.setChannelCode(channelCode);
                        inventorySpaceService.save(storageInventorySpace);

                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    } else {
//                        if (spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&!spaceInventoryList.get(0).getSkuCode().equals(useInventoryInoutDetailForm.getSkuCode())){
//                            throw new BusinessException("此货位已经存放了SKU编码:["+spaceInventoryList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具");
//                        }
//
//                        if (!isCheck&&spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&!spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())){
//                            throw new BusinessException("此货位已经存放了"+spaceInventoryList.get(0).getBusinessType().getDesc()+"的刀具,"+"不可以在存放"+businessType.getDesc()+"的刀具");
//                        }
//                        spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
                        /**if (spaceInventoryList.size() == 0) {
                            Integer currentQuantity = 0;
                            Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                            StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                            storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                            storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventorySpace.setQuantity(newQuantity);
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                            storageInventorySpace.setCompanyId(enterpriseId);
                            storageInventorySpace.setRemark(storageInventorySpace.getBusinessTypeDesc());
                            storageInventorySpace.setEnterpriseCode(enterpriseCode);
                            inventorySpaceService.save(storageInventorySpace);

                            storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                            storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                            storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                            baseMapper.insert(storageInventoryInoutDetail);
                        } else {*/
                            Integer currentQuantity = spaceInventoryList.get(0).getQuantity();
                            Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                            StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                            storageInventorySpace.setId(spaceInventoryList.get(0).getId());
//                            storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                            storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
//                            storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventorySpace.setQuantity(newQuantity);
//                        if (newQuantity==0){
//                            storageInventorySpace.setBusinessType(null);
//                        }else{
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
//                        }

                            inventorySpaceService.updateById(storageInventorySpace);

                            storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                            storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                            storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                            useInventoryInoutDetailForm.setQuantityCurrent(storageInventoryInoutDetail.getQuantityCurrent());
                            useInventoryInoutDetailForm.setQuantityAfter(storageInventoryInoutDetail.getQuantityAfter());
//                            baseMapper.insert(storageInventoryInoutDetail);
//                            useInventoryInoutDetailForm.setStorageInventoryInoutDetailId(storageInventoryInoutDetail.getId());
//                        }


//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }

                    if (skuSingleInventoryList.size() == 0) {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        storageSingleInventoryProduct.setCompanyId(enterpriseId);
                        storageSingleInventoryProduct.setRemark(storageSingleInventoryProduct.getBusinessTypeDesc());
                        storageSingleInventoryProduct.setEnterpriseCode(enterpriseCode);
                        storageSingleInventoryProduct.setChannelCode(channelCode);
                        storageSingleInventoryProduct.setCreator(JwtUtils.getLoginUserId());
                        storageSingleInventoryProduct.setCreatorName(JwtUtils.getLoginUsername());
                        storageSingleInventoryProductService.save(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(0);
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                    } else {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
//                        storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                        storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
//                        storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
//                        log.info("singleInvnetoryProduct:{}", JSON.toJSONString(storageSingleInventoryProduct));
                        storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                    }

                    if (skuInventoryList.size() == 0) {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        storageInventoryProduct.setCompanyId(enterpriseId);
                        storageInventoryProduct.setRemark(storageInventoryProduct.getBusinessTypeDesc());
                        storageInventoryProduct.setEnterpriseCode(enterpriseCode);
                        storageInventoryProduct.setChannelCode(channelCode);
                        inventoryProductService.save(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                    } else {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
//                        storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        inventoryProductService.updateById(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                    }
                    if (isCheck && StorageInventoryInout.BusinessTypeChecked.temp.equals(businessTypeChecked)) {
                        List<Integer> businessTypes = new ArrayList<>();
                        businessTypes.add(StorageInventorySpace.BusinessType.repair.getValue());
                        businessTypes.add(StorageInventorySpace.BusinessType.recycle.getValue());
                        count = inventorySpaceService.count(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCheckCabCode()).eq("space_code", useInventoryInoutDetailForm.getCheckSpaceCode()).in("business_type", businessTypes));
                        if (count == 0) {
                            StorageInventoryCheck storageInventoryCheck = new StorageInventoryCheck();
                            storageInventoryCheck.setStatus(StorageInventoryCheck.Status.checked);
                            storageInventoryCheckService.update(storageInventoryCheck, new QueryWrapper<StorageInventoryCheck>().eq("cab_code", useInventoryInoutDetailForm.getCheckCabCode()).eq("space_code", useInventoryInoutDetailForm.getCheckSpaceCode()).eq("status", StorageInventoryCheck.Status.created.getValue()));
                        }
                    }
                    baseMapper.insert(storageInventoryInoutDetail);
                    useInventoryInoutDetailForm.setStorageInventoryInoutDetailId(storageInventoryInoutDetail.getId());
                } else {
                    throw new BusinessException("出入库类型参数异常");
                }

            }
        } else {
            throw new BusinessException("未提交存放刀具数据");
        }
    }

    @Transactional
    void saveCheckData(List<UseInventoryInoutDetailForm> list, StorageInventoryInout.BusinessType businessType, Long inoutId, StorageInventoryInout.BusinessDetailType businessDetailType) {
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        List<StorageInventoryCheck> storageInventoryChecks = storageInventoryCheckService.list(new QueryWrapper<StorageInventoryCheck>().eq("cab_code", list.get(0).getCabCode()).eq("space_code", list.get(0).getSpaceCode()).eq("status", StorageInventoryCheck.Status.created.getValue()));
        Long checkId = null;
        boolean isFirst = false;
        if (storageInventoryChecks.size() == 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            StorageInventoryCheck storageInventoryCheck = new StorageInventoryCheck();
            String code = dynamicService.getDayNextCode("cab_storage_inventory_check");
            String day = simpleDateFormat.format(new Date());
            storageInventoryCheck.setCode("CH-" + day + "-" + code);
            storageInventoryCheck.setDay(Integer.valueOf(day));
            storageInventoryCheck.setNo(Integer.valueOf(code));
            storageInventoryCheck.setCreator(JwtUtils.getLoginUserId());
            storageInventoryCheck.setCreatorName(JwtUtils.getLoginUsername());
            storageInventoryCheck.setOperationType(StorageInventoryCheck.OperationType.in);
            storageInventoryCheck.setBusinessType(StorageInventoryCheck.BusinessType.jsonCreator(businessType.name()));
            storageInventoryCheck.setStatus(StorageInventoryCheck.Status.created);
            storageInventoryCheck.setCabCode(list.get(0).getCabCode());
            storageInventoryCheck.setSpaceCode(list.get(0).getSpaceCode());
            String isTradeIn = null;
            if(businessDetailType.getDesc().indexOf("以旧换新") != -1){
                isTradeIn = "是";
            }else{
                isTradeIn = "否";
            }
            storageInventoryCheck.setIsTradeIn(isTradeIn);
            storageInventoryCheck.setBusinessDetailType(StorageInventoryCheck.BusinessDetailType.jsonCreator(businessDetailType.name()));
            storageInventoryCheck.setRemark(storageInventoryCheck.getBusinessDetailTypeDesc());
            storageInventoryCheck.setEnterpriseCode(enterpriseCode);
            storageInventoryCheckService.save(storageInventoryCheck);
            checkId = storageInventoryCheck.getId();
            isFirst = true;
        } else {
            checkId = storageInventoryChecks.get(0).getId();
        }
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
            if (isFirst) {
                saveCheckDetail(useInventoryInoutDetailForm, creator, creatorName, checkId, businessType);
            } else {
                List<StorageInventoryCheckDetail> storageInventoryCheckDetails = storageInventoryCheckDetailService.list(new QueryWrapper<StorageInventoryCheckDetail>().eq("check_id", checkId).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                if (storageInventoryCheckDetails.size() == 0) {
                    saveCheckDetail(useInventoryInoutDetailForm, creator, creatorName, checkId, businessType);
                } else {
                    StorageInventoryCheckDetail storageInventoryCheckDetail4Update = new StorageInventoryCheckDetail();
                    storageInventoryCheckDetail4Update.setQuantity(storageInventoryCheckDetails.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
                    storageInventoryCheckDetail4Update.setId(storageInventoryCheckDetails.get(0).getId());
                    storageInventoryCheckDetailService.updateById(storageInventoryCheckDetail4Update);
                }
            }
        }
        StorageInventoryCheckInout storageInventoryCheckInout = new StorageInventoryCheckInout();
        storageInventoryCheckInout.setCheckId(checkId);
        storageInventoryCheckInout.setInoutId(inoutId);
        storageInventoryCheckInout.setEnterpriseCode(enterpriseCode);
        storageInventoryCheckInoutService.save(storageInventoryCheckInout);

    }

    @Transactional
    void saveCheckDetail(UseInventoryInoutDetailForm useInventoryInoutDetailForm, Long creator, String creatorName, Long checkId, StorageInventoryInout.BusinessType businessType) {
        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        List<StorageInventoryCheckDetail> checkDetails = storageInventoryCheckDetailService.list(new QueryWrapper<StorageInventoryCheckDetail>()
                .eq("cab_code", useInventoryInoutDetailForm.getCabCode())
                .eq("space_code", useInventoryInoutDetailForm.getSpaceCode())
                .eq("sku_code", useInventoryInoutDetailForm.getSkuCode())
                .eq("check_id", checkId));
        if (checkDetails.size() == 0) {
            StorageInventoryCheckDetail storageInventoryCheckDetail = new StorageInventoryCheckDetail();
            BeanUtils.copyProperties(useInventoryInoutDetailForm, storageInventoryCheckDetail);
            storageInventoryCheckDetail.setCompanyId(enterpriseId);
            storageInventoryCheckDetail.setId(null);
            storageInventoryCheckDetail.setCreator(creator);
            storageInventoryCheckDetail.setCreatorName(creatorName);
            storageInventoryCheckDetail.setOperationType(StorageInventoryCheckDetail.OperationType.in);
            storageInventoryCheckDetail.setBusinessType(StorageInventoryCheckDetail.BusinessType.jsonCreator(businessType.name()));
            storageInventoryCheckDetail.setCheckId(checkId);
            storageInventoryCheckDetail.setEnterpriseCode(enterpriseCode);
            storageInventoryCheckDetailService.save(storageInventoryCheckDetail);
        } else {
            StorageInventoryCheckDetail storageInventoryCheckDetail4Update = new StorageInventoryCheckDetail();
            storageInventoryCheckDetail4Update.setId(checkDetails.get(0).getId());
            storageInventoryCheckDetail4Update.setQuantity(checkDetails.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
            storageInventoryCheckDetailService.updateById(storageInventoryCheckDetail4Update);
        }


    }

    @Transactional
    Long saveDetail4CheckOut(List<UseInventoryInoutDetailForm> list, Long storageInventoryInoutId, String inOutTypeName, StorageInventoryInout.BusinessType businessType, boolean isCheck, Long checkResultId, StorageInventoryInout.BusinessDetailType businessDetailType, Long checkInventoryInoutId, StorageInventoryInout.BusinessTypeChecked businessTypeChecked) {
        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        Long storageInventoryCheckId = null;
        if (CollectionUtils.isNotEmpty(list)) {
            for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                StorageInventoryInoutDetail storageInventoryInoutDetail = new StorageInventoryInoutDetail();
                BeanUtils.copyProperties(useInventoryInoutDetailForm, storageInventoryInoutDetail);
                storageInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                storageInventoryInoutDetail.setCompanyId(enterpriseId);
                storageInventoryInoutDetail.setId(null);
                storageInventoryInoutDetail.setCreator(creator);
                storageInventoryInoutDetail.setCreatorName(creatorName);
                storageInventoryInoutDetail.setOperationType(StorageInventoryInoutDetail.OperationType.jsonCreator(inOutTypeName));
                storageInventoryInoutDetail.setBusinessType(StorageInventoryInoutDetail.BusinessType.jsonCreator(businessType.name()));
                storageInventoryInoutDetail.setInoutId(storageInventoryInoutId);
                if (isCheck) {
                    storageInventoryInoutDetail.setBusinessTypeChecked(StorageInventoryInoutDetail.BusinessTypeChecked.jsonCreator(businessTypeChecked.name()));
                    storageInventoryInoutDetail.setQuantityChecked(useInventoryInoutDetailForm.getQuantity());
                    if (StorageInventoryInout.BusinessType.losed.equals(businessType)) {
                        storageInventoryInoutDetail.setQuantityChecked(0);
                    }
                }

//                List<StorageInventorySpace> spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("business_type",businessType.getValue()));
//                List<StorageInventorySpace> spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()));
                List<CabinetCargoSpace> cabinetCargoSpaces = cargoSpaceService.list(new QueryWrapper<CabinetCargoSpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("code", useInventoryInoutDetailForm.getSpaceCode()));
                if (cabinetCargoSpaces.size() == 0) {
                    throw new BusinessException("未找到库位");
                }
//                if (CabinetCargoSpace.SpaceNature.personal.equals(cabinetCargoSpaces.get(0).getSpaceNature())){
//                    if (!creator.equals(cabinetCargoSpaces.get(0).getPrincipal())){
//                        throw new BusinessException("柜子编号["+cabinetCargoSpaces.get(0).getCode()+"]为用户的专人存贮,其他用户不能打开");
//                    }
//                }
                List<StorageInventorySpace> spaceInventoryList = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
                    if (cabinetCargoSpaces.get(0).getSpaceType() != null &&
                            (CabinetCargoSpace.SpaceType.common.equals(cabinetCargoSpaces.get(0).getSpaceType()) ||
                                    CabinetCargoSpace.SpaceType.temp.equals(cabinetCargoSpaces.get(0).getSpaceType())) &&
                            (StringUtils.isBlank(cabinetCargoSpaces.get(0).getPrincipal()))

                    ) {
                        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
                        Boolean spaceTempMoreFlag = false;
                        if (systemRuleInfo != null) {
                            spaceTempMoreFlag = systemRuleInfo.getSpaceTempMoreFlag();
                        }
                        int count = storageInventoryKnifeService.count(new QueryWrapper<StorageInventoryKnife>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                        if (!spaceTempMoreFlag && count > 0) {
                            throw new BusinessException("请选择空的库位");
                        }
                    }
                }

                List<StorageInventoryProduct> skuInventoryList = inventoryProductService.list(new QueryWrapper<StorageInventoryProduct>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("business_type", businessType.getValue()).eq("enterprise_code", enterpriseCode));
                List<StorageSingleInventoryProduct> skuSingleInventoryList = storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("business_type", businessType.getValue()));


                if (UseInventoryInout.Type.out.name().equals(inOutTypeName)) {
//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }
//                    if (skuSingleInventoryList.size()==0){
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]上的SKU["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }

//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));
                    log.info("盘验调式，label_code{}",useInventoryInoutDetailForm.getLabelCode());
                    List<StorageInventoryKnife> storageInventoryKnives = storageInventoryKnifeService.list(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                    if (storageInventoryKnives.size() == 0) {
                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(), "未找到柜子编号[" + useInventoryInoutDetailForm.getCabCode() + "]货道[" + useInventoryInoutDetailForm.getSpaceCode() + "]上的SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]刀具产品数据");
                    } else {
                        spaceInventoryList = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                        List<StorageInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()));
                        Integer quantityOut = useInventoryInoutDetailForm.getQuantity();


                        useInventoryInoutDetailForm.setSettingTime(storageInventoryKnives.get(0).getSettingTime());
                        useInventoryInoutDetailForm.setRemainingTime(storageInventoryKnives.get(0).getRemainingTime());
                        useInventoryInoutDetailForm.setLifeUnit(storageInventoryKnives.get(0).getLifeUnit());
                        useInventoryInoutDetailForm.setParentLabelCode(storageInventoryKnives.get(0).getParentLabelCode());
                        useInventoryInoutDetailForm.setDeviceCode(storageInventoryKnives.get(0).getDeviceCode());


                        storageInventoryKnifeService.remove(new QueryWrapper<StorageInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));

                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                        useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.outChecked);
                        if (isCheck) {
                            if (StorageInventoryInout.BusinessType.losed.equals(businessType)) {
                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.outCheckedLose);
                            }
                        }
                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                        useInventoryUserKnifeService.update(useInventoryUserKnife, new QueryWrapper<UseInventoryUserKnife>().eq("code", useInventoryInoutDetailForm.getLabelCode()));
                        UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();
                        if (isCheck &&
                                (StorageInventoryInout.BusinessType.repair.equals(businessType) || StorageInventoryInout.BusinessType.recycle.equals(businessType))) {
                            List<StorageInventoryCheck> storageInventoryChecks = storageInventoryCheckService.list(new QueryWrapper<StorageInventoryCheck>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()).eq("status", StorageInventoryCheck.Status.created.getValue()));
                            if (storageInventoryChecks.size() > 0) {
                                storageInventoryCheckId = storageInventoryChecks.get(0).getId();
                                useInventoryUserKnifeInout.setStorageInventoryCheckId(storageInventoryChecks.get(0).getId());
                            }
                        }


                        useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
                        useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());

                        useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
                        useInventoryUserKnifeInout.setCheckResultId(checkResultId);

//                        useInventoryUserKnifeInout.setCellInventoryInoutId(cellInventoryInoutId);
//                        useInventoryUserKnifeInout.setDeviceCode(deviceCode);
                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.outChecked);
                        useInventoryUserKnifeInout.setCreator(creator);
                        useInventoryUserKnifeInout.setCreatorName(creatorName);
                        useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessTypeDesc());
                        useInventoryUserKnifeInout.setCheckInventoryInoutId(checkInventoryInoutId);
                        useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);

                        if (skuInventoryUserList.size() > 0) {
                            useInventoryUserKnifeInout.setStorageInventoryUserId(skuInventoryUserList.get(0).getId());

                            StorageInventoryUser storageInventoryUser4Update = new StorageInventoryUser();
                            storageInventoryUser4Update.setId(skuInventoryUserList.get(0).getId());
                            storageInventoryUser4Update.setQuantity(skuInventoryUserList.get(0).getQuantity() - quantityOut);
                            if ((skuInventoryUserList.get(0).getQuantity() - quantityOut) <= 0) {
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            } else {
                                inventoryUserService.updateById(storageInventoryUser4Update);
                            }
                        }

                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);


                        /**
                         for(StorageInventoryUser storageInventoryUser:skuInventoryUserList){

                         //                            StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                         storageInventoryUser.setId(storageInventoryUser.getId());
                         //                            storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                         //                            storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                         //                            storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                         //                            storageInventoryUser.setQuantity(newQuantity);
                         //                            if (newQuantity == 0) {
                         //                                storageInventoryUser.setBusinessType(null);
                         //                            storageInventoryUser.setSkuCode(null);
                         if (quantityOut>0){
                         if (quantityOut>=storageInventoryUser.getQuantity()){
                         //                                    inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                         inventoryUserService.removeById(storageInventoryUser.getId());
                         quantityOut=quantityOut-storageInventoryUser.getQuantity();
                         }else{
                         StorageInventoryUser storageInventoryUser4Update=new StorageInventoryUser();
                         storageInventoryUser4Update.setId(storageInventoryUser.getId());
                         storageInventoryUser4Update.setQuantity(storageInventoryUser.getQuantity()-quantityOut);
                         inventoryUserService.updateById(storageInventoryUser4Update);
                         quantityOut=0;
                         }
                         }


                         //                            } else {
                         //                                storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                         //                                inventoryUserService.updateById(storageInventoryUser);
                         //                            }
                         }*/
//                        List<Integer> businessTypes=new ArrayList<>();
//                        businessTypes.add(StorageInventorySpace.BusinessType.repair.getValue());
//                        businessTypes.add(StorageInventorySpace.BusinessType.recycle.getValue());
//                        int count=inventorySpaceService.count(new QueryWrapper<StorageInventorySpace>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).in("business_type",businessTypes));
//                        if (count==0){
//                            StorageInventoryCheck storageInventoryCheck=new StorageInventoryCheck();
//                            storageInventoryCheck.setStatus(StorageInventoryCheck.Status.checked);
//                            storageInventoryCheckService.update(storageInventoryCheck,new QueryWrapper<StorageInventoryCheck>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("status",StorageInventoryCheck.Status.created.getValue()));
//                        }
                        /**
                         Integer quantity=useInventoryInoutDetailForm.getQuantity();
                         //                        if (quantity <= 0) {
                         //                            throw new BusinessException("取数量参数异常");
                         //                        }
                         //                        if (quantity > 0) {
                         //                            quantity = -1 * quantity;
                         //                        }
                         //
                         Integer currentQuantity = spaceInventoryList.get(0).getQuantity();
                         Integer newQuantity = currentQuantity + quantity;
                         //                        if (newQuantity < 0) {
                         //                            throw new BusinessException("SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品库存不足");
                         //                        }
                         //
                         //
                         storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                         //                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                         storageInventoryInoutDetail.setQuantityAfter(0);
                         storageInventoryInoutDetail.setQuantity(quantity);
                         storageInventoryInoutDetail.setCreator(useInventoryInoutDetailForm.getCreator());
                         storageInventoryInoutDetail.setCreatorName(useInventoryInoutDetailForm.getCreatorName());
                         storageInventoryInoutDetail.setModifier(creator);
                         storageInventoryInoutDetail.setModifierName(creatorName);
                         */
//
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }
                    Integer quantity = useInventoryInoutDetailForm.getQuantity();
                    if (quantity <= 0) {
                        throw new BusinessException("取数量参数异常");
                    }
                    if (quantity > 0) {
                        quantity = -1 * quantity;
                    }
                    storageInventoryInoutDetail.setQuantity(quantity);
                    if (spaceInventoryList.size() > 0) {
//                        throw new BusinessException(Result.Code.REQUIRE_REFRESH.getCode(),"未找到柜子编号["+useInventoryInoutDetailForm.getCabCode()+"]货道["+useInventoryInoutDetailForm.getSpaceCode()+"]上的SKU编号["+useInventoryInoutDetailForm.getSkuCode()+"]刀具产品数据");
//                    }else{


                        Integer currentQuantity = spaceInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
                            throw new BusinessException("SKU编号[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品库存不足");
                        }

                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setId(spaceInventoryList.get(0).getId());
                        storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setQuantity(newQuantity);
                        if (newQuantity <= 0) {
                            storageInventorySpace.setBusinessType(null);
//                            storageInventorySpace.setSkuCode(null);
                            inventorySpaceService.removeById(spaceInventoryList.get(0).getId());
                        } else {
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                            inventorySpaceService.updateById(storageInventorySpace);
                        }

                        /**
                        if (skuSingleInventoryList.size() > 0) {
                            StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                            storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
                            storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + quantity);
                            if (storageSingleInventoryProduct.getQuantity() <= 0) {
                                storageSingleInventoryProduct.setBusinessType(null);
//                            storageSingleInventoryProduct.setSkuCode(null);
                                storageSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                            } else {
                                storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                                storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);
                            }
                        }

                        if (skuInventoryList.size() > 0) {
                            StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                            storageInventoryProduct.setId(skuInventoryList.get(0).getId());
                            storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + quantity);
                            if (storageInventoryProduct.getQuantity() <= 0) {
                                storageInventoryProduct.setBusinessType(null);
//                            storageInventoryProduct.setSkuCode(null);
                                inventoryProductService.removeById(skuInventoryList.get(0).getId());
                            } else {
                                storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                                inventoryProductService.updateById(storageInventoryProduct);
                            }
                        }*/
                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }

                    if (skuSingleInventoryList.size() > 0) {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
                        storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + quantity);
                        if (storageSingleInventoryProduct.getQuantity() <= 0) {
                            storageSingleInventoryProduct.setBusinessType(null);
//                            storageSingleInventoryProduct.setSkuCode(null);
                            storageSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                        } else {
                            storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                            storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);
                        }

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                    }

                    if (skuInventoryList.size() > 0) {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setId(skuInventoryList.get(0).getId());
                        storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + quantity);
                        if (storageInventoryProduct.getQuantity() <= 0) {
                            storageInventoryProduct.setBusinessType(null);
//                            storageInventoryProduct.setSkuCode(null);
                            inventoryProductService.removeById(skuInventoryList.get(0).getId());
                        } else {
                            storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                            inventoryProductService.updateById(storageInventoryProduct);
                        }

                        storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                    }
                    baseMapper.insert(storageInventoryInoutDetail);

                    log.info("{}", StorageInventoryInout.BusinessType.repair.equals(businessType));
                    log.info("{}", StorageInventoryInout.BusinessType.recycle.equals(businessType));
                    if (isCheck &&
                            (StorageInventoryInout.BusinessType.repair.equals(businessType) || StorageInventoryInout.BusinessType.recycle.equals(businessType))) {
                        log.info("useInventoryInoutDetailForm check param:{}", JSON.toJSONString(useInventoryInoutDetailForm));
                        List<Integer> businessTypes = new ArrayList<>();
                        businessTypes.add(StorageInventorySpace.BusinessType.repair.getValue());
                        businessTypes.add(StorageInventorySpace.BusinessType.recycle.getValue());
                        int count = inventorySpaceService.count(new QueryWrapper<StorageInventorySpace>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()).in("business_type", businessTypes));
                        if (count == 0) {
                            StorageInventoryCheck storageInventoryCheck = new StorageInventoryCheck();
                            storageInventoryCheck.setStatus(StorageInventoryCheck.Status.checked);
                            storageInventoryCheckService.update(storageInventoryCheck, new QueryWrapper<StorageInventoryCheck>().eq("cab_code", useInventoryInoutDetailForm.getCabCode()).eq("space_code", useInventoryInoutDetailForm.getSpaceCode()).eq("status", StorageInventoryCheck.Status.created.getValue()));
                        }
                    }


                } else if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {

//                    Integer quantity=useInventoryInoutDetailForm.getQuantity();
                    if (useInventoryInoutDetailForm.getQuantity() <= 0) {
                        throw new BusinessException("存数量参数异常");
                    }
//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("cab_code",useInventoryInoutDetailForm.getCabCode()).eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("space_code",useInventoryInoutDetailForm.getSpaceCode()).eq("creator",creator));
//                    List<StorageInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<StorageInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));

//                    if (skuInventoryUserList.size()==0){
//                        Integer currentQuantity=0;
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                    StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                    storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    storageInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
                    storageInventoryUser.setCreator(creator);
                    storageInventoryUser.setCreatorName(creatorName);
                    storageInventoryUser.setCompanyId(enterpriseId);
                    storageInventoryUser.setEnterpriseCode(enterpriseCode);
                    inventoryUserService.save(storageInventoryUser);

//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
//                    }else{
//                        if (skuInventoryUserList.get(0).getQuantity()!=null&&skuInventoryUserList.get(0).getQuantity()>0&&!skuInventoryUserList.get(0).getSkuCode().equals(useInventoryInoutDetailForm.getSkuCode())){
//                            throw new BusinessException("此货位已经存放了SKU编码:["+skuInventoryUserList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具");
//                        }
//
//                        if (!isCheck&&skuInventoryUserList.get(0).getQuantity()!=null&&skuInventoryUserList.get(0).getQuantity()>0&&!skuInventoryUserList.get(0).getBusinessType().name().equals(businessType.name())){
//                            throw new BusinessException("此货位已经存放了"+skuInventoryUserList.get(0).getBusinessType().getDesc()+"的刀具,"+"不可以在存放"+businessType.getDesc()+"的刀具");
//                        }
//
//                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();
//
//                        StorageInventoryUser storageInventoryUser=new StorageInventoryUser();
//                        storageInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        storageInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
//                        storageInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
//                        storageInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
//                        storageInventoryUser.setQuantity(newQuantity);
//                        if (newQuantity==0){
//                            storageInventoryUser.setBusinessType(null);
//                        }else{
//                            storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.jsonCreator(businessType.name()));
//                        }
//
//                        inventoryUserService.updateById(storageInventoryUser);
//
//                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
//                    }
//                    quantity=useInventoryInoutDetailForm.getQuantity();
                    storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    if (spaceInventoryList.size() == 0) {
                        Integer currentQuantity = 0;
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setQuantity(newQuantity);
                        storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                        storageInventorySpace.setCompanyId(enterpriseId);
                        storageInventorySpace.setEnterpriseCode(enterpriseCode);
                        inventorySpaceService.save(storageInventorySpace);

                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    } else {
//                        if (spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&!spaceInventoryList.get(0).getSkuCode().equals(useInventoryInoutDetailForm.getSkuCode())){
//                            throw new BusinessException("此货位已经存放了SKU编码:["+spaceInventoryList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具");
//                        }
//
//                        if (!isCheck&&spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&!spaceInventoryList.get(0).getBusinessType().name().equals(businessType.name())){
//                            throw new BusinessException("此货位已经存放了"+spaceInventoryList.get(0).getBusinessType().getDesc()+"的刀具,"+"不可以在存放"+businessType.getDesc()+"的刀具");
//                        }

                        Integer currentQuantity = spaceInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setId(spaceInventoryList.get(0).getId());
                        storageInventorySpace.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageInventorySpace.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        storageInventorySpace.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setQuantity(newQuantity);
                        if (newQuantity == 0) {
                            storageInventorySpace.setBusinessType(null);
                        } else {
                            storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(businessType.name()));
                        }

                        inventorySpaceService.updateById(storageInventorySpace);

                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        storageInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }

                    if (skuSingleInventoryList.size() == 0) {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        storageSingleInventoryProduct.setCompanyId(enterpriseId);
                        storageSingleInventoryProduct.setEnterpriseCode(enterpriseCode);
                        storageSingleInventoryProduct.setCreator(JwtUtils.getLoginUserId());
                        storageSingleInventoryProduct.setCreatorName(JwtUtils.getLoginUsername());
                        storageSingleInventoryProductService.save(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(0);
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                    } else {
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
                        storageSingleInventoryProduct.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        storageSingleInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
                        storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                    }

                    if (skuInventoryList.size() == 0) {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        storageInventoryProduct.setCompanyId(enterpriseId);
                        storageInventoryProduct.setEnterpriseCode(enterpriseCode);
                        inventoryProductService.save(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                    } else {
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setId(skuInventoryList.get(0).getId());
                        storageInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity() + useInventoryInoutDetailForm.getQuantity());
                        storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(businessType.name()));
                        inventoryProductService.updateById(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                    }
                    baseMapper.insert(storageInventoryInoutDetail);
                } else {
                    throw new BusinessException("出入库类型参数异常");
                }

            }
        } else {
            throw new BusinessException("未提交存放刀具数据");
        }
        return storageInventoryCheckId;
    }

    @Override
    @Transactional
    public boolean check(StorageInventoryInoutDetailForm storageInventoryInoutDetailForm) {
        List<CabinetCargoSpace> cabinetCargoSpaces = cargoSpaceService.list(new QueryWrapper<CabinetCargoSpace>().eq("cab_code", storageInventoryInoutDetailForm.getCabCode()).eq("space_code", storageInventoryInoutDetailForm.getSpaceCode()));
        if (cabinetCargoSpaces.size() != 1) {
            throw new BusinessException("货位未找到");
        }
        check(cabinetCargoSpaces.get(0).getId(), StorageInventoryInout.BusinessType.jsonCreator(storageInventoryInoutDetailForm.getBusinessType().name()), storageInventoryInoutDetailForm.getSkuFlag());
        return true;
    }

    @Override
    @Transactional
    public boolean check(Long spaceId, StorageInventoryInout.BusinessType businessType, boolean skuFlag) {
        Long enterpriseId = JwtUtils.getEnterpriseId();
        CabinetCargoSpaceVO cabinetCargoSpaceVO = cargoSpaceService.get4appById(spaceId);
        if (cabinetCargoSpaceVO == null) {
            throw new BusinessException("货位未找到");
        }
        Map params = new HashMap();
        params.put("cabCode", cabinetCargoSpaceVO.getCabCode());
        params.put("spaceCode", cabinetCargoSpaceVO.getCode());
        List<StorageInventoryUncheckVO> list = inventoryUncheckService.list4app(params);
        List<StorageInventorySpace> inventorySpaces = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", cabinetCargoSpaceVO.getCabCode()).eq("space_code", cabinetCargoSpaceVO.getCode()));

        if ((!StorageInventoryInout.BusinessType.temp.equals(businessType) && list.size() == 0)) {
            throw new BusinessException("未找到盘验任务数据");
        }
        if (inventorySpaces.size() == 0 || inventorySpaces.get(0).getQuantity() == 0) {
            throw new BusinessException("未找到此货位上的库存数据");
        }
        List<StorageInventoryInoutDetailForm> inventoryList = new ArrayList<>();
        for (StorageInventorySpace storageInventorySpace : inventorySpaces) {
//            StorageInventorySpace storageInventorySpace=inventorySpaces.get(0);
            StorageInventoryInoutDetailForm useInventoryInoutDetailForm = new StorageInventoryInoutDetailForm();
            useInventoryInoutDetailForm.setCabCode(storageInventorySpace.getCabCode());
            useInventoryInoutDetailForm.setCabId(storageInventorySpace.getCabId());
            useInventoryInoutDetailForm.setSpaceCode(storageInventorySpace.getSpaceCode());
            useInventoryInoutDetailForm.setSpaceId(storageInventorySpace.getSpaceId());
            useInventoryInoutDetailForm.setSkuCode(storageInventorySpace.getSkuCode());
            useInventoryInoutDetailForm.setSkuId(storageInventorySpace.getSkuId());
            useInventoryInoutDetailForm.setQuantity(storageInventorySpace.getQuantity());
            useInventoryInoutDetailForm.setCompanyId(enterpriseId);
            inventoryList.add(useInventoryInoutDetailForm);
            StorageInventoryInoutDetail storageInventoryInoutDetail = new StorageInventoryInoutDetail();
            BeanUtils.copyProperties(useInventoryInoutDetailForm, storageInventoryInoutDetail);
            saveCheckedResult(storageInventoryInoutDetail, businessType, businessType.name(), storageInventorySpace.getQuantity());
        }


        if (StorageInventoryInout.BusinessType.temp.equals(businessType) && list.size() == 0) {
//            StorageInventoryInoutDetail storageInventoryInoutDetail=new StorageInventoryInoutDetail();
//            BeanUtils.copyProperties(useInventoryInoutDetailForm,storageInventoryInoutDetail);
//            saveCheckedResult(storageInventoryInoutDetail,businessType, businessType.name(),storageInventorySpace.getQuantity());
            return true;
        }

        List<StorageInventoryInoutDetail> checkList = new ArrayList<>();
        String businessTypeChanged = businessType.name();
        String businessTypePre = inventorySpaces.get(0).getBusinessType().name();
//        List<UseInventoryInoutDetailForm> inventoryList=new ArrayList<>();
        for (StorageInventoryUncheckVO uncheckVO : list) {

            StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
            List<StorageInventoryInoutDetail> inoutDetailS = baseMapper.selectList(new QueryWrapper<StorageInventoryInoutDetail>().eq("inout_id", uncheckVO.getInoutId()));
            checkList.addAll(inoutDetailS);
            /**
             if (!businessTypeChanged.equals(businessTypePre)){
             for (StorageInventoryInoutDetail inventoryInoutDetail:inoutDetailS){
             UseInventoryInoutDetailForm useInventoryInoutDetailForm=new UseInventoryInoutDetailForm();
             BeanUtils.copyProperties(inventoryInoutDetail,useInventoryInoutDetailForm);
             useInventoryInoutDetailForm.setId(null);
             inventoryList.add(useInventoryInoutDetailForm);
             }
             }*/
            storageInventoryInout.setBusinessTypeChecked(StorageInventoryInout.BusinessTypeChecked.jsonCreator(businessTypeChanged));
            storageInventoryInout.setId(uncheckVO.getInoutId());
            storageInventoryInout.setStatus(StorageInventoryInout.Status.checked);
            storageInventoryInout.setCheckTime(LocalDateTime.now());
            storageInventoryInout.setCheckUserId(JwtUtils.getLoginUserId());
            storageInventoryInout.setCheckUserName(JwtUtils.getLoginUsername());
            inventoryInoutService.updateById(storageInventoryInout);
            baseMapper.update4Check(businessType.getValue(), uncheckVO.getInoutId());
            inventoryUncheckService.removeById(uncheckVO.getId());


        }
        Long checkedResultId = saveCheckedResult(checkList, businessType, businessTypePre, inventorySpaces.get(0).getQuantity());

//        List<StorageInventoryInoutDetailForm> inventoryList=new ArrayList<>();

//        inventoryList.add(useInventoryInoutDetailForm);

        if (StorageInventoryInout.BusinessType.temp.name().equals(businessTypePre)) {

            if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.temp);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheck, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
//                checkedInventoryInoutDetailService.inventoryIn(inventoryList,checkedResultId, CheckedInventoryInout.BusinessType.repair,CheckedInventoryInout.BusinessTypePre.temp);
            } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.temp);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheck, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
//                checkedInventoryInoutDetailService.inventoryIn(inventoryList,checkedResultId,CheckedInventoryInout.BusinessType.recycle,CheckedInventoryInout.BusinessTypePre.temp);
            } else if (StorageInventoryInout.BusinessType.losed.name().equals(businessTypeChanged)) {
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheckLose, StorageInventoryInout.BusinessTypeChecked.losed, null);
            } else if (skuFlag) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.temp, CheckedInventoryInout.BusinessTypePre.temp);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheckSpec, StorageInventoryInout.BusinessTypeChecked.temp, checkedInventoryInout.getId());
            }

        } else if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypePre)) {
//            this.inventoryOut4Check(inventoryList,StorageInventoryInout.BusinessType.repair,checkedResultId,StorageInventoryInout.BusinessDetailType.repairOutByCheck,StorageInventoryInout.BusinessTypeChecked.repair);
            if (StorageInventoryInout.BusinessType.temp.name().equals(businessTypeChanged)) {
                StorageInventoryInout storageInventoryInout = this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheck, StorageInventoryInout.BusinessTypeChecked.temp, null);
                this.inventoryIn4Check(inventoryList, checkedResultId, StorageInventoryInout.BusinessType.temp, StorageInventoryInout.BusinessDetailType.tempInByCheck, StorageInventoryInout.BusinessTypePre.repair, storageInventoryInout.getId(), storageInventoryInout.getStorageInventoryCheckId());
            } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypeChanged)) {

                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.repair);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheck, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.repair);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheck, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.losed.name().equals(businessTypeChanged)) {
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheckLose, StorageInventoryInout.BusinessTypeChecked.losed, null);
            } else if (skuFlag) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.repair);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheckSpec, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
            }

        } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypePre)) {

            if (StorageInventoryInout.BusinessType.temp.name().equals(businessTypeChanged)) {
                StorageInventoryInout storageInventoryInout = this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheck, StorageInventoryInout.BusinessTypeChecked.temp, null);
                this.inventoryIn4Check(inventoryList, checkedResultId, StorageInventoryInout.BusinessType.temp, StorageInventoryInout.BusinessDetailType.tempInByCheck, StorageInventoryInout.BusinessTypePre.recycle, storageInventoryInout.getId(), storageInventoryInout.getStorageInventoryCheckId());
            } else if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.recycle);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheck, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.recycle);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheck, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.losed.name().equals(businessTypeChanged)) {
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheckLose, StorageInventoryInout.BusinessTypeChecked.losed, null);
            } else if (skuFlag) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.recycle);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheckSpec, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
            }
        }

        return true;
    }

    private List<StorageInventoryInoutDetailForm> combine(List<StorageInventoryInoutDetailForm> list) {
        Map<String, StorageInventoryInoutDetailForm> resultMap = new HashMap<>();
        for (StorageInventoryInoutDetailForm storageInventoryInoutDetailForm : list) {
            String key = storageInventoryInoutDetailForm.getCabCode() + "_" + storageInventoryInoutDetailForm.getSpaceCode() + "_" + storageInventoryInoutDetailForm.getSkuCode();
            if (resultMap.containsKey(key)) {
                StorageInventoryInoutDetailForm val = resultMap.get(key);
                val.setQuantity(val.getQuantity() + storageInventoryInoutDetailForm.getQuantity());
                resultMap.put(key, val);
                resultMap.get(key).getDetailList().add(storageInventoryInoutDetailForm);

            } else {
                StorageInventoryInoutDetailForm storageInventoryInoutDetailFormTarget = new StorageInventoryInoutDetailForm();
                BeanUtils.copyProperties(storageInventoryInoutDetailForm, storageInventoryInoutDetailFormTarget);
                List<StorageInventoryInoutDetailForm> tempList = new ArrayList<>();
                tempList.add(storageInventoryInoutDetailForm);
                storageInventoryInoutDetailFormTarget.setDetailList(tempList);
                resultMap.put(key, storageInventoryInoutDetailFormTarget);
            }
        }
        List<StorageInventoryInoutDetailForm> resultList = new ArrayList<>();
        resultMap.values().forEach(item -> {
            resultList.add(item);
        });
        return resultList;
    }

    private Integer getCheckQuantity(List<StorageInventoryInoutDetailForm> list) {
        Integer sum = 0;
        for (StorageInventoryInoutDetailForm storageInventoryInoutDetailForm : list) {
            sum += storageInventoryInoutDetailForm.getQuantity();
        }
        return sum;
    }


    @Override
    @Transactional
    public boolean check4Wx(StorageInventoryInoutForm storageInventoryInoutForm) throws IOException {
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        StorageInventoryInout.BusinessType businessType = storageInventoryInoutForm.getBusinessType();
        String cabCode = storageInventoryInoutForm.getDetailList().get(0).getCabCode();
        String spaceCode = storageInventoryInoutForm.getDetailList().get(0).getSpaceCode();
        String skuCode = storageInventoryInoutForm.getDetailList().get(0).getSkuCode();
        Map params = new HashMap();
        params.put("cabCode", cabCode);
        params.put("spaceCode", spaceCode);
        List<StorageInventorySpaceVO> inventorySpaces = inventorySpaceService.list4app(params);
        if (inventorySpaces.size() == 0) {
            throw new BusinessException("未找到此货位上的库存数据");
        }
        String businessTypePre = inventorySpaces.get(0).getBusinessType().name();
        if (businessType == null) {
            businessType = StorageInventoryInout.BusinessType.jsonCreator(businessTypePre);
        }
//        CabinetOpenServer.sendMessage(cabCode, spaceCode);

        if (StorageInventoryInout.BusinessType.temp.equals(businessType) && !StorageInventoryInout.BusinessType.temp.name().equals(businessTypePre)) {
            if (inventorySpaces.size() == 1 && inventorySpaces.get(0).getQuantity() == 1 &&
                    (CabinetCargoSpace.SpaceType.temp.equals(inventorySpaces.get(0).getCargoSpaceType()) || CabinetCargoSpace.SpaceType.common.equals(inventorySpaces.get(0).getCargoSpaceType()))) {
                storageInventoryInoutForm.getDetailList().forEach(item -> {
                    item.setTargetCabCode(cabCode);
                    item.setTargetSpaceCode(spaceCode);
                });
            } else {
                List<Cabinet> cabinets = cabinetService.list(new QueryWrapper<Cabinet>().eq("code", cabCode));
                if (cabinets.size() == 0) {
                    throw new BusinessException("未找到柜子编号[" + cabCode + "]的柜子");
                }
                UseInventoryInoutDetailForm useInventoryInoutDetailForm = new UseInventoryInoutDetailForm();
                useInventoryInoutDetailForm.setStorageType(CabinetCargoSpace.SpaceNature.common);
                useInventoryInoutDetailForm.setSkuCode(skuCode);
                cabinets = cabinetService.list(new QueryWrapper<Cabinet>().eq("cabinet_nature", Cabinet.CabinetNature.live.getValue()).eq("belong_cabinet", cabinets.get(0).getBelongCabinet()));
                String cabCodes = "";
                for (Cabinet cabinet : cabinets) {
                    cabCodes += cabinet.getCode() + ",";
                }
                useInventoryInoutDetailForm.setCabCode(cabCodes.substring(0, cabCodes.length() - 1));
                useInventoryInoutDetailForm.setQuantity(1);
//                final CabinetCargoSpaceVO spaceVO = this.getUsableSpaces(useInventoryInoutDetailForm, StorageInventoryInout.BusinessType.temp);
                final CabinetCargoSpaceVO spaceVO = this.getSpaces4OldNew(null, cabCodes, useInventoryInoutDetailForm.getSkuCode(), StorageInventoryInout.BusinessType.temp,useInventoryInoutDetailForm.getQuantity());
                log.info("space data:{}", JSONObject.toJSONString(spaceVO));
                if (spaceVO == null) {
                    if (CabinetCargoSpace.SpaceNature.personal.equals(useInventoryInoutDetailForm.getStorageType())) {
                        throw new BusinessException("未找到可用的专属库位,请先进行库位设置");
                    } else if (CabinetCargoSpace.SpaceNature.specialClass.equals(useInventoryInoutDetailForm.getStorageType())) {
                        throw new BusinessException("未找到可用的专类库位，请先进行库位设置");
                    } else if (CabinetCargoSpace.SpaceNature.common.equals(useInventoryInoutDetailForm.getStorageType())) {
                        throw new BusinessException("未找到可用的公共库位");
                    } else {
                        throw new BusinessException("存贮性质参数错误");
                    }
                }
                CabinetVO cabinetVO = cabinetService.get4appByCode(spaceVO.getCabCode());

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cabCode",spaceVO.getCabCode());
                jsonObject.put("spaceCode",spaceCode);
                jsonObject.put("type","remoteOpen");

                CabinetOpenServer.sendMessage(enterpriseCode,cabinetVO.getBelongCabinet(), jsonObject.toJSONString());
                storageInventoryInoutForm.getDetailList().forEach(item -> {
                    item.setTargetCabCode(spaceVO.getCabCode());
                    item.setTargetSpaceCode(spaceVO.getCode());
                });
            }

        }

        check(storageInventoryInoutForm);
        return true;
    }

    @Override
    @Transactional
    public boolean check(StorageInventoryInoutForm storageInventoryInoutForm) {
        if (CollectionUtil.isEmpty(storageInventoryInoutForm.getDetailList())) {
            throw new BusinessException("缺少盘验明细参数");
        }
        setDefaultVal4Check(storageInventoryInoutForm.getDetailList());
        storageInventoryInoutForm.getDetailList().get(0).setRemark(storageInventoryInoutForm.getRemark());
        String remark = "";
        if (storageInventoryInoutForm.getFlag() == null || storageInventoryInoutForm.getFlag() == false ||
                storageInventoryInoutForm.getSkuFlag() == null || storageInventoryInoutForm.getSkuFlag() == true) {
            storageInventoryInoutForm.setIsCorrect(false);
        }
        if (storageInventoryInoutForm.getFlag() != null && storageInventoryInoutForm.getFlag()) {
            storageInventoryInoutForm.setIsCorrect(true);
            storageInventoryInoutForm.setBusinessTypeCorrect(true);
            storageInventoryInoutForm.setSkuCorrect(true);
        } else {
            storageInventoryInoutForm.setIsCorrect(false);
        }
        if (storageInventoryInoutForm.getSkuFlag() != null && storageInventoryInoutForm.getSkuFlag()) {
            storageInventoryInoutForm.setSkuCorrect(false);
            storageInventoryInoutForm.setBusinessTypeCorrect(true);
            remark = "规格不符";
        } else {
            storageInventoryInoutForm.setSkuCorrect(true);
        }
        storageInventoryInoutForm.getDetailList().get(0).setIsCorrect(storageInventoryInoutForm.getIsCorrect());
        storageInventoryInoutForm.getDetailList().get(0).setBusinessTypeCorrect(storageInventoryInoutForm.getBusinessTypeCorrect());
        storageInventoryInoutForm.getDetailList().get(0).setSkuCorrect(storageInventoryInoutForm.getSkuCorrect());

        StorageInventoryInout.BusinessType businessType = storageInventoryInoutForm.getBusinessType();
//        CabinetCargoSpaceVO cabinetCargoSpaceVO=cargoSpaceService.get4appById(spaceId);
//        if (cabinetCargoSpaceVO==null) {
//            throw new BusinessException("货位未找到");
//        }
//        Map params=new HashMap();
//        params.put("cabCode",cabinetCargoSpaceVO.getCabCode());
//        params.put("spaceCode",cabinetCargoSpaceVO.getCode());
//        List<StorageInventoryUncheckVO> list=inventoryUncheckService.list4app(params);
        String cabCode = storageInventoryInoutForm.getDetailList().get(0).getCabCode();
        String spaceCode = storageInventoryInoutForm.getDetailList().get(0).getSpaceCode();
        List<StorageInventoryInoutDetailForm> inventoryList4Combine = combine(storageInventoryInoutForm.getDetailList());
        List<StorageInventoryInoutDetailForm> inventoryList = storageInventoryInoutForm.getDetailList();
        List<StorageInventorySpace> inventorySpaces = inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code", cabCode).eq("space_code", spaceCode));

//        if ((!StorageInventoryInout.BusinessType.temp.equals(businessType)&&list.size()==0)){
//            throw new BusinessException("未找到盘验任务数据");
//        }
        if (inventorySpaces.size() == 0) {
            throw new BusinessException("未找到此货位上的库存数据");
        }
        if (((storageInventoryInoutForm.getSkuFlag() != null && storageInventoryInoutForm.getSkuFlag())||
                (storageInventoryInoutForm.getFlag() != null && storageInventoryInoutForm.getFlag())
        )&&businessType==null) {
            businessType=StorageInventoryInout.BusinessType.jsonCreator(inventorySpaces.get(0).getBusinessType().name());
            storageInventoryInoutForm.setBusinessType(businessType);
        }
//        List<StorageInventoryInoutDetailForm> inventoryList=storageInventoryInoutForm.getDetailList();
//        for (StorageInventorySpace storageInventorySpace:combineList){
////            StorageInventorySpace storageInventorySpace=inventorySpaces.get(0);
//            StorageInventoryInoutDetailForm useInventoryInoutDetailForm=new StorageInventoryInoutDetailForm();
//            useInventoryInoutDetailForm.setCabCode(storageInventorySpace.getCabCode());
//            useInventoryInoutDetailForm.setCabId(storageInventorySpace.getCabId());
//            useInventoryInoutDetailForm.setSpaceCode(storageInventorySpace.getSpaceCode());
//            useInventoryInoutDetailForm.setSpaceId(storageInventorySpace.getSpaceId());
//            useInventoryInoutDetailForm.setSkuCode(storageInventorySpace.getSkuCode());
//            useInventoryInoutDetailForm.setSkuId(storageInventorySpace.getSkuId());
//            useInventoryInoutDetailForm.setQuantity(storageInventorySpace.getQuantity());
//            useInventoryInoutDetailForm.setCompanyId(BaseDataInit.ENTERPRISE_ID);
//            inventoryList.add(useInventoryInoutDetailForm);
//            StorageInventoryInoutDetail storageInventoryInoutDetail=new StorageInventoryInoutDetail();
//            BeanUtils.copyProperties(useInventoryInoutDetailForm,storageInventoryInoutDetail);
//            saveCheckedResult(storageInventoryInoutDetail,businessType, businessType.name(),storageInventorySpace.getQuantity());
//        }

        List<StorageInventoryInoutDetail> checkList = new ArrayList<>();
        String businessTypeChanged = businessType.name();
        String businessTypePre = inventorySpaces.get(0).getBusinessType().name();

        if (businessTypeChanged == null) {
            businessTypeChanged = businessTypePre;
        }
        log.info("{}", StorageInventoryInout.BusinessType.temp.equals(businessType));
        log.info("{}", StorageInventorySpace.BusinessType.temp.equals(inventorySpaces.get(0).getBusinessType()));
        if (StorageInventoryInout.BusinessType.temp.equals(businessType) && StorageInventorySpace.BusinessType.temp.equals(inventorySpaces.get(0).getBusinessType())) {
//            StorageInventoryInoutDetail storageInventoryInoutDetail=new StorageInventoryInoutDetail();
//            BeanUtils.copyProperties(useInventoryInoutDetailForm,storageInventoryInoutDetail);
//            saveCheckedResult(storageInventoryInoutDetail,businessType, businessType.name(),storageInventorySpace.getQuantity());
            saveCheckedResult(storageInventoryInoutForm, businessTypePre, getCheckQuantity(storageInventoryInoutForm.getDetailList()), inventoryList4Combine);
            return true;
        }
        if (!businessTypeChanged.equals(businessTypePre)) {
            remark = "状态不符";
        }
        if (StorageInventoryInout.BusinessType.losed.equals(storageInventoryInoutForm.getBusinessType())) {
            remark = "缺失";
        }
        storageInventoryInoutForm.setRemark(remark);
        storageInventoryInoutForm.getDetailList().get(0).setRemark(remark);

//        List<StorageInventoryInoutDetail> checkList=new ArrayList<>();
//        String businessTypeChanged=businessType.name();
//        String businessTypePre=inventorySpaces.get(0).getBusinessType().name();
//        List<UseInventoryInoutDetailForm> inventoryList=new ArrayList<>();
//        for (StorageInventoryUncheckVO uncheckVO:list){
//
//            StorageInventoryInout storageInventoryInout=new StorageInventoryInout();
//            List<StorageInventoryInoutDetail> inoutDetailS= baseMapper.selectList(new QueryWrapper<StorageInventoryInoutDetail>().eq("inout_id",uncheckVO.getInoutId()));
//            checkList.addAll(inoutDetailS);
//            /**
//             if (!businessTypeChanged.equals(businessTypePre)){
//             for (StorageInventoryInoutDetail inventoryInoutDetail:inoutDetailS){
//             UseInventoryInoutDetailForm useInventoryInoutDetailForm=new UseInventoryInoutDetailForm();
//             BeanUtils.copyProperties(inventoryInoutDetail,useInventoryInoutDetailForm);
//             useInventoryInoutDetailForm.setId(null);
//             inventoryList.add(useInventoryInoutDetailForm);
//             }
//             }*/
//            storageInventoryInout.setBusinessTypeChecked(StorageInventoryInout.BusinessTypeChecked.jsonCreator(businessTypeChanged));
//            storageInventoryInout.setId(uncheckVO.getInoutId());
//            storageInventoryInout.setStatus(StorageInventoryInout.Status.checked);
//            storageInventoryInout.setCheckTime(LocalDateTime.now());
//            storageInventoryInout.setCheckUserId(JwtUtils.getLoginUserId());
//            storageInventoryInout.setCheckUserName(JwtUtils.getLoginUsername());
//            inventoryInoutService.updateById(storageInventoryInout);
//            baseMapper.update4Check(businessType.getValue(),uncheckVO.getInoutId());
//            inventoryUncheckService.removeById(uncheckVO.getId());
//
//
//        }
//        Long checkedResultId=saveCheckedResult(checkList,businessType,businessTypePre,inventorySpaces.get(0).getQuantity());
        Long checkedResultId = saveCheckedResult(storageInventoryInoutForm, businessTypePre, getCheckQuantity(storageInventoryInoutForm.getDetailList()), inventoryList4Combine);

//        List<StorageInventoryInoutDetailForm> inventoryList=new ArrayList<>();

//        inventoryList.add(useInventoryInoutDetailForm);

        if (StorageInventoryInout.BusinessType.temp.name().equals(businessTypePre)) {

            if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.temp);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheck, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
//                checkedInventoryInoutDetailService.inventoryIn(inventoryList,checkedResultId, CheckedInventoryInout.BusinessType.repair,CheckedInventoryInout.BusinessTypePre.temp);
            } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.temp);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheck, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
//                checkedInventoryInoutDetailService.inventoryIn(inventoryList,checkedResultId,CheckedInventoryInout.BusinessType.recycle,CheckedInventoryInout.BusinessTypePre.temp);
            } else if (StorageInventoryInout.BusinessType.losed.name().equals(businessTypeChanged)) {
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheckLose, StorageInventoryInout.BusinessTypeChecked.losed, null);
            } else if (storageInventoryInoutForm.getSkuFlag() != null && storageInventoryInoutForm.getSkuFlag()) {
//                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.temp, CheckedInventoryInout.BusinessTypePre.temp);
//                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheckSpec, StorageInventoryInout.BusinessTypeChecked.temp, checkedInventoryInout.getId());
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.temp, checkedResultId, StorageInventoryInout.BusinessDetailType.tempOutByCheckSpec, StorageInventoryInout.BusinessTypeChecked.temp, null);
            }

        } else if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypePre)) {
//            this.inventoryOut4Check(inventoryList,StorageInventoryInout.BusinessType.repair,checkedResultId,StorageInventoryInout.BusinessDetailType.repairOutByCheck,StorageInventoryInout.BusinessTypeChecked.repair);
            if (StorageInventoryInout.BusinessType.temp.name().equals(businessTypeChanged)) {
                StorageInventoryInout storageInventoryInout = this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheck, StorageInventoryInout.BusinessTypeChecked.temp, null);
//                StorageInventoryInout storageInventoryInout=this.inventoryOut(list, StorageInventoryInout.BusinessType.temp,null,StorageInventoryInout.BusinessDetailType.tempOut);
                inventoryList.forEach(item -> {
                    item.setCheckCabCode(item.getCabCode());
                    item.setCheckSpaceCode(item.getSpaceCode());
                    item.setCabCode(item.getTargetCabCode());
                    item.setSpaceCode(item.getTargetSpaceCode());
                });
                this.inventoryIn4Check(inventoryList, checkedResultId, StorageInventoryInout.BusinessType.temp, StorageInventoryInout.BusinessDetailType.tempInByCheck, StorageInventoryInout.BusinessTypePre.repair, storageInventoryInout.getId(), storageInventoryInout.getStorageInventoryCheckId());
            } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypeChanged)) {

                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.repair);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheck, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.repair);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheck, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.losed.name().equals(businessTypeChanged)) {
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheckLose, StorageInventoryInout.BusinessTypeChecked.losed, null);
            } else if (storageInventoryInoutForm.getSkuFlag() != null && storageInventoryInoutForm.getSkuFlag()) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.repair);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.repair, checkedResultId, StorageInventoryInout.BusinessDetailType.repairOutByCheckSpec, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
            }

        } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypePre)) {

            if (StorageInventoryInout.BusinessType.temp.name().equals(businessTypeChanged)) {
                StorageInventoryInout storageInventoryInout = this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheck, StorageInventoryInout.BusinessTypeChecked.temp, null);
                inventoryList.forEach(item -> {
                    item.setCheckCabCode(item.getCabCode());
                    item.setCheckSpaceCode(item.getSpaceCode());
                    item.setCabCode(item.getTargetCabCode());
                    item.setSpaceCode(item.getTargetSpaceCode());
                });
                this.inventoryIn4Check(inventoryList, checkedResultId, StorageInventoryInout.BusinessType.temp, StorageInventoryInout.BusinessDetailType.tempInByCheck, StorageInventoryInout.BusinessTypePre.recycle, storageInventoryInout.getId(), storageInventoryInout.getStorageInventoryCheckId());
            } else if (StorageInventoryInout.BusinessType.repair.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.repair, CheckedInventoryInout.BusinessTypePre.recycle);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheck, StorageInventoryInout.BusinessTypeChecked.repair, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.recycle.name().equals(businessTypeChanged)) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.recycle);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheck, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
            } else if (StorageInventoryInout.BusinessType.losed.name().equals(businessTypeChanged)) {
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheckLose, StorageInventoryInout.BusinessTypeChecked.losed, null);
            } else if (storageInventoryInoutForm.getSkuFlag() != null && storageInventoryInoutForm.getSkuFlag()) {
                CheckedInventoryInout checkedInventoryInout = checkedInventoryInoutDetailService.inventoryIn(inventoryList, checkedResultId, CheckedInventoryInout.BusinessType.recycle, CheckedInventoryInout.BusinessTypePre.recycle);
                this.inventoryOut4Check(inventoryList, StorageInventoryInout.BusinessType.recycle, checkedResultId, StorageInventoryInout.BusinessDetailType.recycleOutByCheckSpec, StorageInventoryInout.BusinessTypeChecked.recycle, checkedInventoryInout.getId());
            }
        }
        sendMsg(checkedResultId);
        return true;
    }


    void sendMsg(Long checkedResultId) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            syncData(checkedResultId);
                        } catch (Exception e) {
                            log.error("syn fail", e);
                        }

                    }
                });
            }
        });
    }


    // 数据同步
    public void syncData(Long checkedResultId) {
        CheckedResult checkedResult = checkedResultService.getById(checkedResultId);
        if (checkedResult != null) {
            // 同步cab_checked_result
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                checkedResult.setSkuCode(checkedResult.getEnterpriseCode() + "-" + checkedResult.getSkuCode());
                checkedResult.setUniqCode(checkedResult.getEnterpriseCode() + "-" + checkedResultId);
                jsonObject.put("data", checkedResult);
                PulsarUtils.send(topicUrl + PulsarCommons.CAB_CHECKED_RESULT, jsonObject.toJSONString());
            } catch (Exception e) {
                log.error("sync err 同步cab_checked_result失败", e);
//                checkedResult.setIsSync(CheckedResult.IsSync.no);
//                checkedResultService.updateById(CheckedResult);
                CheckedResult checkedResultUpdate = new CheckedResult();
                checkedResultUpdate.setId(checkedResult.getId());
                checkedResultUpdate.setIsSync(CheckedResult.IsSync.no);
                checkedResultService.updateById(checkedResultUpdate);
            }

            // 同步cab_checked_result_detail
            List<CheckedResultDetail> resultDetailList = checkedResultDetailService.list(
                    new LambdaQueryWrapper<CheckedResultDetail>().eq(CheckedResultDetail::getResultId, checkedResultId));
            if (resultDetailList.size() > 0) {
                Stream.iterate(0, i -> i + 1).limit(resultDetailList.size()).forEach(i -> {
                    try {
                        resultDetailList.get(i).setSkuCode(resultDetailList.get(i).getEnterpriseCode() + "-" + resultDetailList.get(i).getSkuCode());
                        resultDetailList.get(i).setResultUniqCode(checkedResult.getUniqCode());
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("type", "addOrUpdate");
                        jsonObject.put("data", resultDetailList.get(i));
                        PulsarUtils.send(topicUrl + PulsarCommons.CAB_CHECKED_RESULT_DETAIL, jsonObject.toJSONString());
                    } catch (Exception e) {
                        log.error("sync err 同步cab_checked_result_detail失败 ",e);
//                        resultDetailList.get(i).setIsSyns(0);
//                        checkedResultDetailService.updateById(resultDetailList.get(i));
                        CheckedResultDetail checkedResultDetailUpdate = new CheckedResultDetail();
                        checkedResultDetailUpdate.setId(resultDetailList.get(i).getId());
                        checkedResultDetailUpdate.setIsSyns(0);
                        checkedResultDetailService.updateById(checkedResultDetailUpdate);
                    }
                });
            }

        }

    }

    @Override
    @Transactional
    public boolean checkOrder(Long orderId, StorageInventoryInout.BusinessType businessType) {
        StorageInventoryInoutVO storageInventoryInoutVO = inventoryInoutService.get4appById(orderId);
        if (storageInventoryInoutVO == null) {
            throw new BusinessException("未找到待盘验任务");
        }
        Map paramMap = new HashMap();
        paramMap.put("inoutId", orderId);
        List<CabinetCargoSpaceVO> list = cargoSpaceService.list4app(paramMap);
        if (list.size() == 0) {
            throw new BusinessException("未找到待盘验任务");
        }
        check(list.get(0).getId(), businessType, false);
        return true;
    }

    @Transactional
    Long saveCheckedResult(StorageInventoryInoutForm storageInventoryInoutForm, String businessTypePre, Integer quantityCheck, List<StorageInventoryInoutDetailForm> combineInventoryList) {
        List<Cabinet> cabinets=cabinetService.list(new QueryWrapper<Cabinet>().eq("code",combineInventoryList.get(0).getCabCode()));
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        String creatorName = JwtUtils.getLoginUsername();
        Long creator = JwtUtils.getLoginUserId();
        Long resultId = saveCheckedResult(storageInventoryInoutForm.getDetailList().get(0), storageInventoryInoutForm.getBusinessType(), businessTypePre, quantityCheck, storageInventoryInoutForm.getFlag(), storageInventoryInoutForm.getCategoryId());
        for (StorageInventoryInoutDetailForm storageInventoryInoutDetailForm : combineInventoryList) {
            CheckedResultDetail checkedResultDetail = new CheckedResultDetail();
            //生成盘验明细编号
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
            String code = dynamicService.getDayMaxCode("code","cab_checked_result_detail");
            String day = simpleDateFormat.format(new Date());
            checkedResultDetail.setCode("RED-"+day+"-"+code);

            checkedResultDetail.setResultId(resultId);
            checkedResultDetail.setCabCode(storageInventoryInoutDetailForm.getCabCode());
            checkedResultDetail.setCabId(storageInventoryInoutDetailForm.getCabId());
            checkedResultDetail.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
            checkedResultDetail.setSkuId(storageInventoryInoutDetailForm.getSkuId());
            checkedResultDetail.setSpaceCode(storageInventoryInoutDetailForm.getSpaceCode());
            checkedResultDetail.setSpaceId(storageInventoryInoutDetailForm.getSpaceId());
            checkedResultDetail.setQuantity(storageInventoryInoutDetailForm.getQuantity());
            checkedResultDetail.setQuantityPack(storageInventoryInoutDetailForm.getQuantityPack());
            checkedResultDetail.setBusinessType(CheckedResultDetail.BusinessType.jsonCreator(businessTypePre));
            checkedResultDetail.setBusinessTypeChecked(CheckedResultDetail.BusinessTypeChecked.jsonCreator(storageInventoryInoutForm.getBusinessType().name()));
            if (StorageInventoryInout.BusinessTypeChecked.losed.equals(storageInventoryInoutForm.getBusinessType())) {
                checkedResultDetail.setQuantityChecked(0);
            }
            checkedResultDetail.setCreator(creator);
            checkedResultDetail.setCostCenter(JwtUtils.getCostCenter());
            checkedResultDetail.setCreatorName(creatorName);
            checkedResultDetail.setEnterpriseCode(enterpriseCode);
            if (StorageInventoryInout.BusinessType.temp.name().equals(storageInventoryInoutForm.getBusinessType().name())) {
                checkedResultDetail.setOperationType(CheckedResultDetail.OperationType.in);
            } else {
                checkedResultDetail.setOperationType(CheckedResultDetail.OperationType.out);
            }
            checkedResultDetail.setRemark(storageInventoryInoutForm.getRemark());
            if (cabinets.size()>0){
                checkedResultDetail.setMainCabCode(cabinets.get(0).getBelongCabinet());
            }
            checkedResultDetailService.save(checkedResultDetail);
            List<String> labelCodeList = new ArrayList<>();
            for (StorageInventoryInoutDetailForm detailForm : storageInventoryInoutDetailForm.getDetailList()) {
                List<StorageInventoryKnife> storageInventoryKnives= storageInventoryKnifeService.list(new QueryWrapper<StorageInventoryKnife>().eq("label_code",detailForm.getLabelCode()));
                CheckedResultLabel checkedResultLabel = new CheckedResultLabel();
                BeanUtils.copyProperties(checkedResultDetail, checkedResultLabel);
                checkedResultLabel.setId(null);
                checkedResultLabel.setResultDetailId(checkedResultDetail.getId());
                checkedResultLabel.setLabelCode(detailForm.getLabelCode());
                checkedResultLabel.setBusinessType(CheckedResultLabel.BusinessType.jsonCreator(businessTypePre));
                checkedResultLabel.setBusinessTypeChecked(CheckedResultLabel.BusinessTypeChecked.jsonCreator(storageInventoryInoutForm.getBusinessType().name()));
                checkedResultLabel.setRemark(storageInventoryInoutForm.getRemark());
                checkedResultLabel.setIsCorrect(storageInventoryInoutForm.getIsCorrect());
                checkedResultLabel.setCreator(creator);
                checkedResultLabel.setCreatorName(creatorName);
                if(storageInventoryKnives.size()>0){
                    checkedResultLabel.setInCreatorName(storageInventoryKnives.get(0).getCreatorName());
                    checkedResultLabel.setPrice(storageInventoryKnives.get(0).getPrice());
                    checkedResultLabel.setDeviceCode(storageInventoryKnives.get(0).getDeviceCode());
                    checkedResultLabel.setWorkOrderId(storageInventoryKnives.get(0).getWorkOrderId());
                    checkedResultDetail.setPrice(storageInventoryKnives.get(0).getPrice());
                    if(storageInventoryKnives.get(0).getPrice() != null){
                        checkedResultDetail.setTotal(storageInventoryKnives.get(0).getPrice().multiply(new BigDecimal(checkedResultDetail.getQuantity())).setScale(2,BigDecimal.ROUND_HALF_UP));
                    }
                }
                checkedResultDetailService.updateById(checkedResultDetail);
                checkedResultLabelService.save(checkedResultLabel);

                labelCodeList.add(detailForm.getLabelCode());
            }
            // 通过盘验结果ID查询盘验结果信息
            CheckedResult checkedResult = checkedResultService.getById(resultId);
            // 添加刀具生命周期  --  盘验
            CutterLifeCycle.Status status = CutterLifeCycle.Status.check;
            if (storageInventoryInoutForm.getFlag() != null && !storageInventoryInoutForm.getFlag()
                    && storageInventoryInoutForm.getSkuFlag() != null && storageInventoryInoutForm.getSkuFlag()
                    && storageInventoryInoutForm.getBusinessType() == null) { // 规格不相符
                status = CutterLifeCycle.Status.checkForSpecDiscrepancy;
            }else{
                if(checkedResultDetail.getBusinessTypeChecked().equals(CheckedResultDetail.BusinessTypeChecked.temp)){ // 暂存
                    status = CutterLifeCycle.Status.checkForTemporaryStorage;
                }else if(checkedResultDetail.getBusinessTypeChecked().equals(CheckedResultDetail.BusinessTypeChecked.repair)){ // 报修
                    status = CutterLifeCycle.Status.checkForRepair;
                }else if(checkedResultDetail.getBusinessTypeChecked().equals(CheckedResultDetail.BusinessTypeChecked.recycle)){ // 报废
                    status = CutterLifeCycle.Status.checkForScrap;
                }else if(checkedResultDetail.getBusinessTypeChecked().equals(CheckedResultDetail.BusinessTypeChecked.losed)){ // 缺失
                    status = CutterLifeCycle.Status.checkForLoss;
                }
            }
            cutterLifeCycleService.addLifeCycle(labelCodeList, status, null, null, checkedResult.getCode(), null);
        }
        return resultId;
    }

    Long saveCheckedResult(StorageInventoryInoutDetail storageInventoryInoutDetail, StorageInventoryInout.BusinessType businessType, String businessTypePre, Integer quantityCheck) {
        Long enterpriseId = JwtUtils.getEnterpriseId();
        CheckedResult checkedResult = new CheckedResult();
        checkedResult.setCabCode(storageInventoryInoutDetail.getCabCode());
        checkedResult.setCabId(storageInventoryInoutDetail.getCabId());
        checkedResult.setSkuCode(storageInventoryInoutDetail.getSkuCode());
        checkedResult.setSkuId(storageInventoryInoutDetail.getSkuId());
        checkedResult.setSpaceCode(storageInventoryInoutDetail.getSpaceCode());
        checkedResult.setSpaceId(storageInventoryInoutDetail.getSpaceId());
        checkedResult.setQuantity(storageInventoryInoutDetail.getQuantity());
        checkedResult.setStatus(CheckedResult.Status.checked);
        checkedResult.setBusinessType(CheckedResult.BusinessType.jsonCreator(businessType.name()));
        checkedResult.setBusinessTypePre(CheckedResult.BusinessTypePre.jsonCreator(businessTypePre));
        checkedResult.setCreator(JwtUtils.getLoginUserId());
        checkedResult.setCreatorName(JwtUtils.getLoginUsername());
        checkedResult.setQuantity(quantityCheck);
        checkedResult.setIsCorrect(businessType.name().equals(businessTypePre));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getDayNextCode("cab_checked_result");
        String day = simpleDateFormat.format(new Date());
        checkedResult.setCode("RE-" + day + "-" + code);
        checkedResult.setDay(Integer.valueOf(day));
        checkedResult.setNo(Integer.valueOf(code));
        checkedResult.setCompanyId(enterpriseId);
        checkedResultService.save(checkedResult);
        return checkedResult.getId();
    }

    Long saveCheckedResult(StorageInventoryInoutDetailForm storageInventoryInoutDetail, StorageInventoryInout.BusinessType businessType, String businessTypePre, Integer quantityCheck, Boolean correctFlag, Long causeCategoryId) {
        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        String departmentName = JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        List<StorageInventoryCheck> storageInventoryChecks = storageInventoryCheckService.list(new QueryWrapper<StorageInventoryCheck>().eq("cab_code", storageInventoryInoutDetail.getCabCode()).eq("space_code", storageInventoryInoutDetail.getSpaceCode()).eq("status", StorageInventoryCheck.Status.created.getValue()));
        CheckedResult checkedResult = new CheckedResult();
        if (storageInventoryChecks.size() > 0) {
            checkedResult.setCheckId(storageInventoryChecks.get(0).getId());
        }
        checkedResult.setCabCode(storageInventoryInoutDetail.getCabCode());
        checkedResult.setCabId(storageInventoryInoutDetail.getCabId());
        checkedResult.setSkuCode(storageInventoryInoutDetail.getSkuCode());
        checkedResult.setSkuId(storageInventoryInoutDetail.getSkuId());
        checkedResult.setSpaceCode(storageInventoryInoutDetail.getSpaceCode());
        checkedResult.setSpaceId(storageInventoryInoutDetail.getSpaceId());
        checkedResult.setQuantity(storageInventoryInoutDetail.getQuantity());
        checkedResult.setStatus(CheckedResult.Status.checked);
        checkedResult.setBusinessType(CheckedResult.BusinessType.jsonCreator(businessType.name()));
        checkedResult.setBusinessTypePre(CheckedResult.BusinessTypePre.jsonCreator(businessTypePre));
        checkedResult.setCreator(JwtUtils.getLoginUserId());
        checkedResult.setCreatorName(JwtUtils.getLoginUsername());
        checkedResult.setQuantity(quantityCheck);
//        checkedResult.setIsCorrect(businessType.name().equals(businessTypePre));
        checkedResult.setIsCorrect(storageInventoryInoutDetail.getIsCorrect());
//        checkedResult.setIsCorrect(correctFlag);
        checkedResult.setIsCorrect(storageInventoryInoutDetail.getIsCorrect());
        checkedResult.setSkuCorrect(storageInventoryInoutDetail.getSkuCorrect());
        checkedResult.setBusinessTypeCorrect(businessType.name().equals(businessTypePre));
        checkedResult.setCategoryId(causeCategoryId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getDayNextCode("cab_checked_result");
        String day = simpleDateFormat.format(new Date());
        checkedResult.setCode("RE-" + day + "-" + code);
        checkedResult.setDay(Integer.valueOf(day));
        checkedResult.setNo(Integer.valueOf(code));
        checkedResult.setCompanyId(enterpriseId);
        checkedResult.setEnterpriseCode(enterpriseCode);
        checkedResult.setRemark(storageInventoryInoutDetail.getRemark());
        checkedResult.setDepartmentName(departmentName);
        checkedResult.setDepartmentId(JwtUtils.getDepartmentId());
        checkedResult.setRoleName(roleName);
        checkedResultService.save(checkedResult);
        return checkedResult.getId();
    }

    Long saveCheckedResult(List<StorageInventoryInoutDetail> checkList, StorageInventoryInout.BusinessType businessType, String businessTypePre, Integer quantityCheck) {
        if (CollectionUtils.isNotEmpty(checkList)) {
            StorageInventoryInoutDetail storageInventoryInoutDetail = checkList.get(0);
            Long checkedResultId = saveCheckedResult(storageInventoryInoutDetail, businessType, businessTypePre, quantityCheck);
            for (StorageInventoryInoutDetail inventoryInoutDetail : checkList) {
                CheckedResultDetail checkedResultDetail = new CheckedResultDetail();
                //生成盘验明细编号
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
                String code = dynamicService.getDayMaxCode("code","cab_checked_result_detail");
                String day = simpleDateFormat.format(new Date());
                checkedResultDetail.setCode("RED-"+day+"-"+code);

                checkedResultDetail.setResultId(checkedResultId);
                checkedResultDetail.setStorageInoutId(inventoryInoutDetail.getInoutId());
                checkedResultDetailService.save(checkedResultDetail);
            }
            return checkedResultId;
        }
        return null;
    }


    @Override
    @Transactional
    public boolean sign(Long orderId, BigDecimal repairPrice, Integer quantitySign) {
        if (quantitySign <= 0) {
            throw new BusinessException("签收数量参数不能小于零");
        }
        StorageInventoryInoutVO storageInventoryInoutVO = inventoryInoutService.get4appById(orderId);
        if (StorageInventoryInout.Status.signed.equals(storageInventoryInoutVO.getStatus())) {
            throw new BusinessException("此订单已签收");
        }
        List<StorageInventoryInoutDetail> inventoryInoutDetails = baseMapper.selectList(new QueryWrapper<StorageInventoryInoutDetail>().eq("inout_id", orderId));
        if (quantitySign > inventoryInoutDetails.get(0).getQuantity()) {
            throw new BusinessException("签收数量不能大于订单数量");
        }
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        storageInventoryInout.setId(orderId);
        storageInventoryInout.setSignUserId(JwtUtils.getLoginUserId());
        storageInventoryInout.setSignUserName(JwtUtils.getLoginUsername());
        storageInventoryInout.setSignTime(LocalDateTime.now());
        storageInventoryInout.setStatus(StorageInventoryInout.Status.signed);
        inventoryInoutService.updateById(storageInventoryInout);
        baseMapper.update4Sign(repairPrice, quantitySign, orderId);
        useInventoryInoutDetailService.inventoryIn4RepairOrderSign(inventoryInoutDetails, orderId, UseInventoryInout.BusinessType.repairOrderSign);
        return true;
    }

    @Override
    @Transactional
    public boolean notify(Long checkResultId, Long supplierId, String supplierName) {
        CheckedResult checkedResult = new CheckedResult();
        checkedResult.setId(checkResultId);
        checkedResult.setStatus(CheckedResult.Status.notified);
        checkedResult.setNotifyUserId(JwtUtils.getLoginUserId());
        checkedResult.setNotifyUserName(JwtUtils.getLoginUsername());
        checkedResult.setNotifyTime(LocalDateTime.now());
        checkedResult.setSupplierId(supplierId);
        checkedResult.setSupplierName(supplierName);
        checkedResultService.updateById(checkedResult);
        inventoryInoutService.update4Notify(StorageInventoryInout.Status.notified.getValue(), checkedResult.getNotifyUserId(), checkedResult.getNotifyUserName(), checkResultId, supplierId, supplierName);
        //notify platform
        return true;
    }

    @Override
    public Page<StorageInventoryInoutDetailVO> toDoTask(Page page) {
        List<StorageInventoryInoutDetailVO> list = baseMapper.toDoTask(page);
        page.setRecords(list);
        return page;
    }


    @Override
    public List<ScrapApplyVO> selTaskPro(String id) {
        List<ScrapApplyVO> list = baseMapper.selTaskPro(id);
        return list;
    }

    @Override
    public Page<ScrapApplyVO> diskTask(Page page) {
        List<ScrapApplyVO> list = baseMapper.diskTask(page);
        page.setRecords(list);
        return page;
    }

    @Override
    public ScrapApplyVO getCabinet(String cabCode) {

        ScrapApplyVO cabinet = baseMapper.getCabinet(cabCode);
        return cabinet;
    }

    @Override
    public Page<ScrapApplyVO> diskStorage(Map<String, Object> params, Page page) {
        List<ScrapApplyVO> list = baseMapper.diskStorage(params, page);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<ScrapApplyVO> diskResult(Page<ScrapApplyVO> page, Map<String, Object> params) {
        List<ScrapApplyVO> list = baseMapper.diskResult(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<ScrapApplyVO> diskResultNormal(Page<ScrapApplyVO> page, Map<String, Object> params) {
        List<ScrapApplyVO> list = baseMapper.diskResultNormal(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<ScrapApplyVO> repairOrder() {

        return baseMapper.repairOrder();
    }

    // 同步数据
    private void syncDate(StorageInventoryInout storageInventoryInout) {
        String enterpriseCode=storageInventoryInout.getEnterpriseCode();
//        DynamicDataSource.name.set(enterpriseCode.toLowerCase());
        String uniqCode = enterpriseCode +"-"+ storageInventoryInout.getId();
//        List<EnterpricceId> enterpricceIdList = enterpricceIdService.list();
        //数据同步storageInventoryInout
        try {
            StorageInventoryInoutDTO storageInventoryInoutDTO = new StorageInventoryInoutDTO();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(StorageInventoryInoutDTO.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(storageInventoryInout, storageInventoryInoutDTO, copyOptions);
            List<StorageInventoryInoutDetail> list = this.list(new QueryWrapper<StorageInventoryInoutDetail>().eq("inout_id", storageInventoryInout.getId()));
            for (StorageInventoryInoutDetail storageInventoryInoutDetail : list) {
                storageInventoryInoutDetail.setSkuCode(enterpriseCode+"-"+storageInventoryInoutDetail.getSkuCode());
                storageInventoryInoutDetail.setInoutUniqCode(uniqCode);
                storageInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
            }
            storageInventoryInoutDTO.setDetails(list);
            JSONObject json = (JSONObject) JSONObject.toJSON(storageInventoryInoutDTO);
            json.put("uniqCode", uniqCode);
//            json.put("enterpriseId", enterpricceIdList.get(0).getEnterpriseId());
            json.put("idOfEnterprise",storageInventoryInoutDTO.getId());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", json);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_INVENTORY_INOUT_TOPIC, jsonObject.toJSONString());
            storageInventoryInout.setIsSyns(StorageInventoryInout.IsSyns.yes);
            inventoryInoutService.updateById(storageInventoryInout);
        } catch (PulsarClientException e) {
            //同步失败时，改变数据状态。 定时器再执行同步
            StorageInventoryInout storageInventoryInoutUpdate=new StorageInventoryInout();
            storageInventoryInoutUpdate.setId(storageInventoryInout.getId());
            storageInventoryInoutUpdate.setIsSyns(StorageInventoryInout.IsSyns.no);
            inventoryInoutService.updateById(storageInventoryInoutUpdate);
            log.error("push mq fail",e);
        }

        List<StorageInventoryInoutDetail> storageInventoryInoutDetails = baseMapper.selectList(new QueryWrapper<StorageInventoryInoutDetail>().eq("inout_id", storageInventoryInout.getId()));
        JSONArray array = new JSONArray();
        for (StorageInventoryInoutDetail storageInventoryInoutDetail : storageInventoryInoutDetails) {
            JSONObject json = (JSONObject) JSONObject.toJSON(storageInventoryInoutDetail);
//            json.put("enterpriseId", enterpricceIdList.get(0).getEnterpriseId());
            array.add(json);
        }
        /*//数据同步storageInventoryInoutDetails
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", array);
            PulsarUtils.send(topicUrl+ PulsarCommons.STORAGE_INVENTORY_INOUT_DETAILS_TOPIC,jsonObject.toJSONString());
            for (StorageInventoryInoutDetail storageInventoryInoutDetail : storageInventoryInoutDetails) {
                storageInventoryInoutDetail.setIsSyns(StorageInventoryInoutDetail.IsSyns.yes);
                baseMapper.updateById(storageInventoryInoutDetail);
            }

        }catch (PulsarClientException e){
            //同步失败时，改变数据状态。 定时器再执行同步
            for (StorageInventoryInoutDetail storageInventoryInoutDetail : storageInventoryInoutDetails) {
                storageInventoryInoutDetail.setIsSyns(StorageInventoryInoutDetail.IsSyns.no);
                baseMapper.updateById(storageInventoryInoutDetail);
            }
            e.printStackTrace();
        }*/


        //将3张库存表进项查询
        List<StorageInventoryProduct> inventoryProductList = new ArrayList<>();
        List<StorageInventorySpace> inventorySpaceList = new ArrayList<>();
        List<StorageSingleInventoryProduct> singleInventoryProductList = new ArrayList<>();
        for (StorageInventoryInoutDetail storageInventoryInoutDetail : storageInventoryInoutDetails) {
            List<StorageInventoryProduct> inventoryProduct = inventoryProductService.list(new QueryWrapper<StorageInventoryProduct>()
                    .eq("sku_code", storageInventoryInoutDetail.getSkuCode())
                    .eq("business_type",storageInventoryInout.getBusinessType().getValue()));
            if (inventoryProduct != null&&inventoryProduct.size()>0) {
                inventoryProductList.addAll(inventoryProduct);
            }else {
                StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                storageInventoryProduct.setSkuCode(storageInventoryInoutDetail.getSkuCode());
                storageInventoryProduct.setCabCode(storageInventoryInoutDetail.getCabCode());
                storageInventoryProduct.setQuantity(0);
                storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.jsonCreator(storageInventoryInoutDetail.getBusinessType().name()));
                storageInventoryProduct.setEnterpriseCode(storageInventoryInoutDetail.getEnterpriseCode());
                inventoryProductList.add(storageInventoryProduct);
            }
            StorageInventorySpace inventorySpace = inventorySpaceService.getOne(new QueryWrapper<StorageInventorySpace>().eq("sku_code", storageInventoryInoutDetail.getSkuCode())
                    .eq("space_code", storageInventoryInoutDetail.getSpaceCode())
                    .eq("cab_code", storageInventoryInoutDetail.getCabCode())
                    .eq("business_type",storageInventoryInout.getBusinessType().getValue()));
            if (inventorySpace != null) {
                inventorySpaceList.add(inventorySpace);
            }else {
                StorageInventorySpace i = new StorageInventorySpace();
                inventorySpace = i;
                inventorySpace.setEnterpriseCode(storageInventoryInoutDetail.getEnterpriseCode());
                inventorySpace.setSpaceCode(storageInventoryInoutDetail.getSpaceCode());
                inventorySpace.setBusinessType(StorageInventorySpace.BusinessType.jsonCreator(storageInventoryInoutDetail.getBusinessType().name()));
                inventorySpace.setSkuCode(storageInventoryInoutDetail.getSkuCode());
                inventorySpace.setCabCode(storageInventoryInoutDetail.getCabCode());
                inventorySpace.setQuantity(0);
                inventorySpaceList.add(inventorySpace);
            }
            List<StorageSingleInventoryProduct> singleInventoryProduct = storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>().eq("sku_code", storageInventoryInoutDetail.getSkuCode())
                    .eq("cab_code", storageInventoryInoutDetail.getCabCode())
                    .eq("business_type",storageInventoryInout.getBusinessType().getValue()));
            if (singleInventoryProduct != null&&singleInventoryProduct.size()>0) {
                singleInventoryProductList.addAll(singleInventoryProduct);
            }else {
                StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                storageSingleInventoryProduct.setSkuCode(storageInventoryInoutDetail.getSkuCode());
                storageSingleInventoryProduct.setCabCode(storageInventoryInoutDetail.getCabCode());
                storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.jsonCreator(storageInventoryInoutDetail.getBusinessType().name()));
                storageSingleInventoryProduct.setQuantity(0);
                storageSingleInventoryProduct.setEnterpriseCode(storageInventoryInoutDetail.getEnterpriseCode());
                singleInventoryProductList.add(storageSingleInventoryProduct);

            }
        }
//        log.info("singleInventoryProductList:{}",JSON.toJSONString(singleInventoryProductList));
        //数据同步StorageInventoryProduct
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            for (StorageInventoryProduct inventoryProduct : inventoryProductList) {
                inventoryProduct.setSkuCode(enterpriseCode+"-"+inventoryProduct.getSkuCode());
            }
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(inventoryProductList));
//            log.info("inventory product list:{}",jsonArray.toJSONString());
            for (Object o : jsonArray) {
                JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(o));
//                jsonObject1.put("enterpriseId", enterpricceIdList.get(0).getEnterpriseId());
            }
            jsonObject.put("data", jsonArray);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_INVENTORY_PRODUCT_TOPIC, jsonObject.toJSONString());
//            log.info("inventory product:{}",jsonObject.toJSONString());
        } catch (PulsarClientException e) {
            // 同步失败时，改变数据状态。 定时器再执行同步
            for (StorageInventoryProduct inventoryProduct : inventoryProductList) {
                if (inventoryProduct.getId()!=null){
                    StorageInventoryProduct storageInventoryProductUpdate=new StorageInventoryProduct();
                    storageInventoryProductUpdate.setId(inventoryProduct.getId());
                    storageInventoryProductUpdate.setIsSyns(StorageInventoryProduct.IsSyns.no);
                    inventoryProductService.updateById(storageInventoryProductUpdate);
                }

            }
            log.error("push mq fail",e);
        }
        //数据同步StorageInventorySpace
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            for (StorageInventorySpace storageInventorySpace : inventorySpaceList) {
                storageInventorySpace.setSkuCode(enterpriseCode+"-"+storageInventorySpace.getSkuCode());
            }
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(inventorySpaceList));
            for (Object o : jsonArray) {
                JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(o));
//                jsonObject1.put("enterpriseId", enterpricceIdList.get(0).getEnterpriseId());
            }
            jsonObject.put("data", jsonArray);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_INVENTORY_SPACE_TOPIC, jsonObject.toJSONString());

        } catch (PulsarClientException e) {
            // 同步失败时，改变数据状态。 定时器再执行同步
            for (StorageInventorySpace inventorySpace : inventorySpaceList) {
                if(inventorySpace.getId()!=null){
                    StorageInventorySpace storageInventorySpaceUpdate=new StorageInventorySpace();
                    storageInventorySpaceUpdate.setId(inventorySpace.getId());
                    storageInventorySpaceUpdate.setIsSyns(StorageInventorySpace.IsSyns.no);
                    inventorySpaceService.updateById(storageInventorySpaceUpdate);
                }

            }
            log.error("push mq fail",e);
        }

        //数据同步StorageSingleInventoryProduct
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            for (StorageSingleInventoryProduct singleInventoryProduct : singleInventoryProductList) {
                singleInventoryProduct.setSkuCode(enterpriseCode+"-"+singleInventoryProduct.getSkuCode());
            }
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(singleInventoryProductList));
//            log.info("single inventory product list:{}",jsonArray.toJSONString());
            for (Object o : jsonArray) {
                JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(o));
//                jsonObject1.put("enterpriseId", enterpricceIdList.get(0).getEnterpriseId());
            }
            jsonObject.put("data", jsonArray);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_SINGLE_INVENTORY_PRODUCT_TOPIC, jsonObject.toJSONString());
//            log.info("single inventory product:{}",jsonObject.toJSONString());
        } catch (PulsarClientException e) {
            // 同步失败时，改变数据状态。 定时器再执行同步
            for (StorageSingleInventoryProduct singleInventoryProduct : singleInventoryProductList) {
                if (singleInventoryProduct.getId()!=null){
                    StorageSingleInventoryProduct storageSingleInventoryProductUpdate=new StorageSingleInventoryProduct();
                    storageSingleInventoryProductUpdate.setId(singleInventoryProduct.getId());
                    storageSingleInventoryProductUpdate.setIsSyns(StorageSingleInventoryProduct.IsSyns.no);
                    storageSingleInventoryProductService.updateById(storageSingleInventoryProductUpdate);
                }

            }
            e.printStackTrace();
        }
    }

    /**
     * 同步数据定时任务
     */
    //todo 未设置定时任务时间
    //@Scheduled(cron = "0/3 * * * * ?")
    public void syncTask() {
        List<StorageInventoryInout> inventoryInoutList = inventoryInoutService.list(new QueryWrapper<StorageInventoryInout>().eq("is_syns", StorageInventoryInout.IsSyns.no.getValue()));
        if (inventoryInoutList != null && inventoryInoutList.size() > 0) {
            for (StorageInventoryInout storageInventoryInout : inventoryInoutList) {
                String uniqCode = JwtUtils.getEnterpriseCode() + storageInventoryInout.getId();
                //数据同步storageInventoryInout
                try {
                    JSONObject json = (JSONObject) JSONObject.toJSON(storageInventoryInout);
                    json.put("uniqCode", uniqCode);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "addOrUpdate");
                    jsonObject.put("data", json);
                    PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_INVENTORY_INOUT_TOPIC, jsonObject.toJSONString());
                    //成功后改为已同步
                    storageInventoryInout.setIsSyns(StorageInventoryInout.IsSyns.yes);
                    inventoryInoutService.updateById(storageInventoryInout);

                } catch (PulsarClientException e) {
                    e.printStackTrace();
                }

            }
        }

        //同步详情表
        List<StorageInventoryInoutDetail> storageInventoryInoutDetails = baseMapper.selectList(new QueryWrapper<StorageInventoryInoutDetail>().eq("is_syns", StorageInventoryInoutDetail.IsSyns.no.getValue()));
        JSONArray array = new JSONArray();
        for (StorageInventoryInoutDetail storageInventoryInoutDetail : storageInventoryInoutDetails) {
            JSONObject jsonDetail = (JSONObject) JSONObject.toJSON(storageInventoryInoutDetail);
            jsonDetail.put("inoutUniqCode", JwtUtils.getEnterpriseCode()+ storageInventoryInoutDetail.getInoutId());
            array.add(jsonDetail);
        }
        try {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("type", "addOrUpdate");
            jsonObject1.put("data", array);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_INVENTORY_INOUT_DETAILS_TOPIC, jsonObject1.toJSONString());
            for (StorageInventoryInoutDetail storageInventoryInoutDetail : storageInventoryInoutDetails) {
                storageInventoryInoutDetail.setIsSyns(StorageInventoryInoutDetail.IsSyns.yes);
                baseMapper.updateById(storageInventoryInoutDetail);
            }
        } catch (PulsarClientException exception) {
            exception.printStackTrace();
        }


        //将3张库存表进项查询
        List<StorageInventoryProduct> inventoryProductList = new ArrayList<>();
        List<StorageInventorySpace> inventorySpaceList = new ArrayList<>();
        List<StorageSingleInventoryProduct> singleInventoryProductList = new ArrayList<>();
        List<StorageInventoryProduct> inventoryProduct = inventoryProductService.list(new QueryWrapper<StorageInventoryProduct>().eq("is_syns", StorageInventoryProduct.IsSyns.no.getValue()));
        if (inventoryProduct != null) {
            inventoryProductList = inventoryProduct;
        }
        StorageInventorySpace inventorySpace = inventorySpaceService.getOne(new QueryWrapper<StorageInventorySpace>().eq("is_syns", StorageInventorySpace.IsSyns.no.getValue()));
        if (inventorySpace != null) {
            inventorySpaceList.add(inventorySpace);
        }
        List<StorageSingleInventoryProduct> singleInventoryProduct = storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>().eq("is_syns", StorageSingleInventoryProduct.IsSyns.no.getValue()));
        if (singleInventoryProduct != null) {
            singleInventoryProductList = singleInventoryProduct;
        }
        //数据同步StorageInventoryProduct
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", inventoryProductList);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_INVENTORY_PRODUCT_TOPIC, jsonObject.toJSONString());
            for (StorageInventoryProduct inventoryProductForm : inventoryProductList) {
                inventoryProductForm.setIsSyns(StorageInventoryProduct.IsSyns.yes);
                inventoryProductService.updateById(inventoryProductForm);
            }
        } catch (PulsarClientException e) {
            e.printStackTrace();
        }
        //数据同步StorageInventorySpace
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", inventorySpaceList);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_INVENTORY_SPACE_TOPIC, jsonObject.toJSONString());
            for (StorageInventorySpace inventorySpaceForm : inventorySpaceList) {
                inventorySpaceForm.setIsSyns(StorageInventorySpace.IsSyns.yes);
                inventorySpaceService.updateById(inventorySpaceForm);
            }
        } catch (PulsarClientException e) {
            e.printStackTrace();
        }

        //数据同步StorageSingleInventoryProduct
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", singleInventoryProductList);
            PulsarUtils.send(topicUrl + PulsarCommons.STORAGE_SINGLE_INVENTORY_PRODUCT_TOPIC, jsonObject.toJSONString());
            for (StorageSingleInventoryProduct singleInventoryProductForm : singleInventoryProductList) {
                singleInventoryProductForm.setIsSyns(StorageSingleInventoryProduct.IsSyns.yes);
                storageSingleInventoryProductService.updateById(singleInventoryProductForm);
            }
        } catch (PulsarClientException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    @Override
    public void latticeCabinetUp(OrderReceiveLoadForm orderReceiveLoadForm) {
        //setDefaultValFromDb(orderReceiveLoadForm);
        if(null == orderReceiveLoadForm.getPackId() || orderReceiveLoadForm.getPackId().equals(0)){
            throw new BusinessException("上货异常:产品["+orderReceiveLoadForm.getSkuCode()+"],没有包装方式参数");
        }
        ProductPackVO productPackVO =productPackService.get4appById(orderReceiveLoadForm.getPackId());
        if(null == productPackVO) {
            throw new BusinessException("上货异常:产品["+orderReceiveLoadForm.getSkuCode()+"],包装方式记录不存在");
        }
        orderReceiveLoadForm.setPackId(productPackVO.getId());
        orderReceiveLoadForm.setPackName(productPackVO.getName());
        orderReceiveLoadForm.setUnitName(productPackVO.getPackUnitName());
        orderReceiveLoadForm.setQuantityPackUnit(productPackVO.getBaseRate());

        List<OrderReceiveLoadDetailForm> detailList=new ArrayList<>();
        OrderReceiveLoadDetailForm orderReceiveLoadDetailForm=new OrderReceiveLoadDetailForm();
        orderReceiveLoadDetailForm.setCabCode(orderReceiveLoadForm.getCabCode());
        orderReceiveLoadDetailForm.setSkuCode(orderReceiveLoadForm.getSkuCode());
        orderReceiveLoadDetailForm.setSpaceCode(orderReceiveLoadForm.getSpaceCode());
        orderReceiveLoadDetailForm.setQuantity(orderReceiveLoadForm.getQuantity());
        orderReceiveLoadDetailForm.setQuantityPackUnit(orderReceiveLoadForm.getQuantityPackUnit());
        orderReceiveLoadDetailForm.setPackId(orderReceiveLoadForm.getPackId());
        orderReceiveLoadDetailForm.setPackName(orderReceiveLoadForm.getPackName());
        orderReceiveLoadDetailForm.setUnitName(orderReceiveLoadForm.getUnitName());
        orderReceiveLoadDetailForm.setQuantityPack(orderReceiveLoadForm.getQuantity()*orderReceiveLoadForm.getQuantityPackUnit());
        detailList.add(orderReceiveLoadDetailForm);
        orderReceiveLoadForm.setDetailList(detailList);
        latticeCabinetBatchUp(orderReceiveLoadForm);
    }




    @Transactional
    public void latticeCabinetBatchUp(OrderReceiveLoadForm orderReceiveLoadForm) {
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        boolean warehouseInventoryFlag=false;
        if (systemRuleInfo!=null){
            warehouseInventoryFlag=systemRuleInfo.getWarehouseInventoryFlag();
        }
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        String channelCode = JwtUtils.getChannelCode();
        String roleName = JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        if (CollectionUtil.isEmpty(orderReceiveLoadForm.getDetailList())){
            throw new BusinessException("缺少上货明细参数");
        }
        StorageInventoryInoutForm storageInventoryInoutForm = new StorageInventoryInoutForm();
        CellInventoryInoutForm cellInventoryInoutForm=new CellInventoryInoutForm();
        List<StorageInventoryInoutDetailForm> detailList=new ArrayList<>();
        List<CellInventoryInoutDetailForm> cellInventoryInoutDetailList=new ArrayList<>();
        for(OrderReceiveLoadDetailForm orderReceiveLoadDetailForm:orderReceiveLoadForm.getDetailList()){
            StorageInventoryInoutDetailForm storageInventoryInoutDetailForm=new StorageInventoryInoutDetailForm();
            storageInventoryInoutDetailForm.setCabCode(orderReceiveLoadDetailForm.getCabCode());
            storageInventoryInoutDetailForm.setSkuCode(orderReceiveLoadDetailForm.getSkuCode());
            storageInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadDetailForm.getSpaceCode());
            storageInventoryInoutDetailForm.setQuantity(orderReceiveLoadDetailForm.getQuantity());
            storageInventoryInoutDetailForm.setQuantityPackUnit(orderReceiveLoadDetailForm.getQuantityPackUnit());
            storageInventoryInoutDetailForm.setPackId(orderReceiveLoadDetailForm.getPackId());
            storageInventoryInoutDetailForm.setPackName(orderReceiveLoadDetailForm.getPackName());
            storageInventoryInoutDetailForm.setUnitName(orderReceiveLoadDetailForm.getUnitName());
            detailList.add(storageInventoryInoutDetailForm);
            CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
            cellInventoryInoutDetailForm.setCabCode(orderReceiveLoadDetailForm.getCabCode());
            cellInventoryInoutDetailForm.setSkuCode(orderReceiveLoadDetailForm.getSkuCode());
            cellInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadDetailForm.getSpaceCode());
            cellInventoryInoutDetailForm.setQuantity(orderReceiveLoadDetailForm.getQuantity());
            cellInventoryInoutDetailForm.setQuantityPackUnit(orderReceiveLoadDetailForm.getQuantityPackUnit());
            cellInventoryInoutDetailForm.setPackId(orderReceiveLoadDetailForm.getPackId());
            cellInventoryInoutDetailForm.setPackName(orderReceiveLoadDetailForm.getPackName());
            cellInventoryInoutDetailForm.setUnitName(orderReceiveLoadDetailForm.getUnitName());
            cellInventoryInoutDetailList.add(cellInventoryInoutDetailForm);
        }
        storageInventoryInoutForm.setDetailList(detailList);
        cellInventoryInoutForm.setDetailList(cellInventoryInoutDetailList);
        if (warehouseInventoryFlag){
            cabInventoryProductService.checkWarehouseInventory4Load(cellInventoryInoutForm.getDetailList());
        }
        //添加暂存柜
        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        BeanUtils.copyProperties(storageInventoryInoutForm,storageInventoryInout);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String code=dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("INS-"+day+"-"+code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(creator);
        storageInventoryInout.setCreatorName(creatorName);
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.in);
        storageInventoryInout.setEnterpriseCode(enterpriseCode);
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setDepartmentName(departmentName);
        storageInventoryInout.setRoleId(roleId);
        storageInventoryInout.setRoleName(roleName);
        storageInventoryInout.setChannelCode(channelCode);
        storageInventoryInoutForm.setCreator(creator);
        storageInventoryInoutForm.setCreatorName(creatorName);
        //添加上货数量
        OrderReceiveLoad orderReceiveLoad=new OrderReceiveLoad();
        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoad);
        code=dynamicService.getDayNextCode("ord_order_receive_load");
        orderReceiveLoad.setCode("GZ-"+day+"-"+code);
        orderReceiveLoad.setDay(Integer.valueOf(day));
        orderReceiveLoad.setNo(Integer.valueOf(code));
        orderReceiveLoad.setCreator(JwtUtils.getLoginUserId());
        orderReceiveLoad.setCreatorName(JwtUtils.getLoginUsername());
        orderReceiveLoad.setEnterpriseCode(enterpriseCode);
        orderReceiveLoad.setType(OrderReceiveLoad.Type.selfLoad);
        orderReceiveLoad.setDepartmentName(departmentName);
        orderReceiveLoad.setDepartmentId(departmentId);
        orderReceiveLoad.setRoleName(roleName);
        orderReceiveLoad.setRoleId(roleId);
        orderReceiveLoad.setChannelCode(channelCode);
        orderReceiveLoadService.save(orderReceiveLoad);
        //添加上货数量详细
        saveReceiveLoadDetail(orderReceiveLoadForm,orderReceiveLoad.getId());
        storageInventoryInout.setEnterpriseCode(enterpriseCode);
        storageInventoryInout.setBusinessType(StorageInventoryInout.BusinessType.exhibit);
        storageInventoryInout.setBusinessDetailType(StorageInventoryInout.BusinessDetailType.exhibit);
        storageInventoryInout.setRemark(StorageInventoryInout.BusinessDetailType.exhibit.getDesc());
        storageInventoryInout.setTotal(getTotal2(storageInventoryInoutForm.getDetailList()));
        inventoryInoutService.save(storageInventoryInout);
        //添加相关明细
        saveLatticeCabinetDetail(storageInventoryInoutForm.getDetailList(),storageInventoryInout.getId(),StorageInventoryInout.OperationType.in.name());
    }

    @Transactional
    public void saveReceiveLoadDetail(OrderReceiveLoadForm orderReceiveLoadForm,Long loadId){
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String channelCode=JwtUtils.getEnterpriseCode();
        if(CollectionUtil.isNotEmpty(orderReceiveLoadForm.getDetailList())){
            for (OrderReceiveLoadDetailForm orderReceiveLoadDetailForm:orderReceiveLoadForm.getDetailList()){
                OrderReceiveLoadDetail orderReceiveLoadDetail=new OrderReceiveLoadDetail();
                BeanUtils.copyProperties(orderReceiveLoadDetailForm,orderReceiveLoadDetail);
                orderReceiveLoadDetail.setLoadId(loadId);
                orderReceiveLoadDetail.setEnterpriseCode(enterpriseCode);
                orderReceiveLoadDetail.setChannelCode(channelCode);
                orderReceiveLoadDetailService.save(orderReceiveLoadDetail);
            }
        }
    }

    @Transactional
    public void saveLatticeCabinetDetail(List<StorageInventoryInoutDetailForm> list,Long inventoryInoutId,String inOutTypeName){
        List<Cabinet> cabinets=cabinetService.list(new QueryWrapper<Cabinet>().eq("code",list.get(0).getCabCode()));
        String mainCabCode=null;
        if (cabinets.size()>0){
            mainCabCode=cabinets.get(0).getBelongCabinet();
        }
        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String channelCode=JwtUtils.getChannelCode();
        if (CollectionUtils.isNotEmpty(list)){
            for (StorageInventoryInoutDetailForm storageInventoryInoutDetailForm:list){
                if (storageInventoryInoutDetailForm.getQuantityPackUnit()==null){
                    storageInventoryInoutDetailForm.setQuantityPackUnit(1);
                }
                StorageInventoryInoutDetail storageInventoryInoutDetail = new StorageInventoryInoutDetail();
                BeanUtils.copyProperties(storageInventoryInoutDetailForm,storageInventoryInoutDetail);
                storageInventoryInoutDetail.setId(null);
                storageInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                storageInventoryInoutDetail.setCompanyId(enterpriseId);
                storageInventoryInoutDetail.setOperationType(StorageInventoryInoutDetail.OperationType.jsonCreator(inOutTypeName));
                storageInventoryInoutDetail.setInoutId(inventoryInoutId);
                storageInventoryInoutDetail.setLoadingType(StorageInventoryInoutDetail.LoadingType.grid);
                storageInventoryInoutDetail.setChannelCode(channelCode);
                storageInventoryInoutDetail.setMainCabCode(mainCabCode);
                storageInventoryInoutDetail.setCreator(creator);
                storageInventoryInoutDetail.setCreatorName(creatorName);

                Integer quantityPack=null;
                Integer quantityPackUnit=null;


                List<StorageInventorySpace> spaceInventoryList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>()
                        .eq("cab_code",storageInventoryInoutDetailForm.getCabCode())
                        .eq("space_code",storageInventoryInoutDetailForm.getSpaceCode()));
                if(StorageInventoryInout.OperationType.out.name().equals(inOutTypeName)&&spaceInventoryList.size()>0){
                    storageInventoryInoutDetailForm.setQuantityPackUnit(spaceInventoryList.get(0).getQuantityPackUnit());
                }

                //List<ProductDetail> productDetails = productDetailService.listBySkuCode(storageInventoryInoutDetailForm.getSkuCode());
                QueryWrapper productQueryWrapper = new QueryWrapper();
                productQueryWrapper.eq("sku_code", storageInventoryInoutDetailForm.getSkuCode());
                ProductDetail productDetail = productDetailService.getOne(productQueryWrapper);

//                List<StorageInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<StorageInventoryUser>()
//                        .eq("cab_code", storageInventoryInoutDetailForm.getCabCode())
//                        .eq("sku_code", storageInventoryInoutDetailForm.getSkuCode())
//                        .eq("space_code", storageInventoryInoutDetailForm.getSpaceCode()));
                if (StorageInventoryInout.OperationType.out.name().equals(inOutTypeName)||StorageInventoryInout.OperationType.out.name().equals(inOutTypeName)){
                    List<StorageInventorySpace> spaceSkuList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>()
                            .eq("cab_code",storageInventoryInoutDetailForm.getCabCode())
                            .eq("space_code",storageInventoryInoutDetailForm.getSpaceCode())
                            .eq("sku_code",storageInventoryInoutDetailForm.getSkuCode()));
                    List<StorageSingleInventoryProduct> skuSingleInventoryList=storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>()
                            .eq("cab_code",storageInventoryInoutDetailForm.getCabCode())
                            .eq("sku_code",storageInventoryInoutDetailForm.getSkuCode()).eq("quantity_pack_unit",storageInventoryInoutDetailForm.getQuantityPackUnit()));
                    List<StorageInventoryProduct> skuInventoryList=inventoryProductService.list(new QueryWrapper<StorageInventoryProduct>()
                            .eq("sku_code",storageInventoryInoutDetailForm.getSkuCode())
                            .eq("enterprise_code",enterpriseCode).eq("quantity_pack_unit",storageInventoryInoutDetailForm.getQuantityPackUnit()));
                    if (spaceSkuList.size()==0){
                        throw new BusinessException("未找到柜子编号["+storageInventoryInoutDetailForm.getCabCode()+"],货道编号["+storageInventoryInoutDetailForm.getSpaceCode()+"]上的刀具产品");
                    }else{
                        if (spaceSkuList.get(0).getQuantityPackUnit()!=null){
                            storageInventoryInoutDetailForm.setQuantityPackUnit(spaceSkuList.get(0).getQuantityPackUnit());
                        }

                        quantityPack=storageInventoryInoutDetailForm.getQuantityPackUnit()*storageInventoryInoutDetailForm.getQuantity();
                        quantityPackUnit=storageInventoryInoutDetailForm.getQuantityPackUnit();
//                        packId=spaceInventoryList.get(0).getPackId();


                        storageInventoryInoutDetail.setPackName(spaceInventoryList.get(0).getPackName());
                        storageInventoryInoutDetail.setPackId(spaceInventoryList.get(0).getPackId());
                        storageInventoryInoutDetail.setUnitName(spaceInventoryList.get(0).getUnitName());
                        storageInventoryInoutDetailForm.setQuantityPack(quantityPack);
                        storageInventoryInoutDetailForm.setQuantityPackUnit(storageInventoryInoutDetail.getQuantityPackUnit());
                        storageInventoryInoutDetailForm.setPackName(storageInventoryInoutDetail.getPackName());
                        storageInventoryInoutDetailForm.setPackId(storageInventoryInoutDetail.getPackId());
                        storageInventoryInoutDetailForm.setUnitName(storageInventoryInoutDetail.getUnitName());

                        storageInventoryInoutDetailForm.setSkuCode(spaceSkuList.get(0).getSkuCode());
                        Integer quantity=storageInventoryInoutDetailForm.getQuantity();
                        if (quantity<=0){
                            throw new BusinessException("领取数量参数异常");
                        }
                        if (quantity>0){
                            quantity=-1*quantity;
                        }
                        if(quantityPack>0){
                            quantityPack=-1*quantityPack;
                        }

                        Integer currentQuantity=spaceSkuList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+quantity;
                        if (newQuantity<0){
                            throw new BusinessException("柜子编号["+storageInventoryInoutDetailForm.getCabCode()+"],货道编号["+storageInventoryInoutDetailForm.getSpaceCode()+"]上的刀具产品库存不足");
                        }
                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setId(spaceSkuList.get(0).getId());
                        storageInventorySpace.setQuantity(newQuantity);
                        //                        if (quantityPack!=null){
                        Integer currentQuantityPack=spaceSkuList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventorySpace.setQuantityPack(currentQuantityPack+quantityPack);
                        storageInventorySpace.setQuantityPackUnit(quantityPackUnit);
//                        }
                        if (newQuantity<=0){
//                            inventorySpaceService.removeById(spaceSkuList.get(0).getId());
                            storageInventorySpace.setQuantity(0);
                            storageInventorySpace.setQuantityPack(0);
                        }
//                        else{
                            inventorySpaceService.updateById(storageInventorySpace);
//                        }
                        storageInventoryInoutDetail.setQuantityPackCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackAfter(currentQuantityPack+quantityPack);
                        if(skuSingleInventoryList.size()>0){
                            StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                            storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
                            storageSingleInventoryProduct.setCabCode(storageInventoryInoutDetailForm.getCabCode());
                            storageSingleInventoryProduct.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                            storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity()+quantity);
                            //                            if (quantityPack!=null){
                            currentQuantityPack=skuSingleInventoryList.get(0).getQuantityPack();
                            if (currentQuantityPack==null){
                                currentQuantityPack=0;
                            }
                            storageSingleInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                            storageSingleInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                            }
                            if (storageSingleInventoryProduct.getQuantity()<=0){
//                                storageSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                                storageSingleInventoryProduct.setQuantity(0);
                                storageSingleInventoryProduct.setQuantityPack(0);
                            }
//                            else{
                                storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);
//                            }
                            storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                            storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());

                            storageInventoryInoutDetail.setQuantityPackSingleCabCurrent(currentQuantityPack);
                            storageInventoryInoutDetail.setQuantityPackSingleCabAfter(storageSingleInventoryProduct.getQuantityPack());

                        }
                        if(skuInventoryList.size()>0){
                            StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                            storageInventoryProduct.setId(skuInventoryList.get(0).getId());
                            storageInventoryProduct.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                            storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity()+quantity);
                            //                            if (quantityPack!=null){
                            currentQuantityPack=skuInventoryList.get(0).getQuantityPack();
                            if (currentQuantityPack==null){
                                currentQuantityPack=0;
                            }
                            storageInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                            storageInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                            }
                            if (storageInventoryProduct.getQuantity()<=0){
                                storageInventoryProduct.setQuantity(0);
                                storageInventoryProduct.setQuantityPack(0);
//                                inventoryProductService.removeById(skuInventoryList.get(0).getId());
                            }
//                            else{
                                inventoryProductService.updateById(storageInventoryProduct);
//                            }

                            storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                            storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());

                            storageInventoryInoutDetail.setQuantityPackCabCurrent(currentQuantityPack);
                            storageInventoryInoutDetail.setQuantityPackCabAfter(storageInventoryProduct.getQuantityPack());
                        }
                        /**
                        if (skuInventoryUserList.size() > 0) {
                            StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                            storageInventoryUser.setId(skuInventoryUserList.get(0).getId());
                            storageInventoryUser.setQuantity(skuInventoryUserList.get(0).getQuantity() - quantity);
                            if ((skuInventoryUserList.get(0).getQuantity() - quantity) <= 0) {
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            } else {
                                inventoryUserService.updateById(storageInventoryUser);
                            }
                        }*/
                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                        storageInventoryInoutDetail.setQuantity(quantity);

                        storageInventoryInoutDetail.setBusinessType(StorageInventoryInoutDetail.BusinessType.unload);
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }
                }else if(StorageInventoryInout.OperationType.in.name().equals(inOutTypeName)){
                    List<StorageInventorySpace> spaceSkuList=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>()
                            .eq("cab_code",storageInventoryInoutDetailForm.getCabCode())
                            .eq("space_code",storageInventoryInoutDetailForm.getSpaceCode())
                            .eq("sku_code",storageInventoryInoutDetailForm.getSkuCode())
                            .eq("business_type",StorageInventoryInoutDetail.BusinessType.exhibit.getValue()));
                    List<StorageSingleInventoryProduct> skuSingleInventoryList=storageSingleInventoryProductService.list(new QueryWrapper<StorageSingleInventoryProduct>()
                            .eq("cab_code",storageInventoryInoutDetailForm.getCabCode())
                            .eq("sku_code",storageInventoryInoutDetailForm.getSkuCode()).eq("quantity_pack_unit",storageInventoryInoutDetailForm.getQuantityPackUnit())
                            .eq("business_type",StorageInventoryInoutDetail.BusinessType.exhibit.getValue()));
                    List<StorageInventoryProduct> skuInventoryList=inventoryProductService.list(new QueryWrapper<StorageInventoryProduct>()
                            .eq("sku_code",storageInventoryInoutDetailForm.getSkuCode())
                            .eq("enterprise_code",enterpriseCode).eq("quantity_pack_unit",storageInventoryInoutDetailForm.getQuantityPackUnit())
                            .eq("business_type",StorageInventoryInoutDetail.BusinessType.exhibit.getValue()));

                    quantityPack=storageInventoryInoutDetailForm.getQuantityPackUnit()*storageInventoryInoutDetailForm.getQuantity();
                    quantityPackUnit=storageInventoryInoutDetailForm.getQuantityPackUnit();
                    storageInventoryInoutDetailForm.setQuantityPack(quantityPack);
                    Long packId=storageInventoryInoutDetailForm.getPackId();

                    storageInventoryInoutDetail.setBusinessType(StorageInventoryInoutDetail.BusinessType.exhibit);
//                    List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>()
//                            .eq("sku_code", storageInventoryInoutDetailForm.getSkuCode()));
                    List<CabinetCargoSpace> lanes=cargoSpaceService.list(new QueryWrapper<CabinetCargoSpace>()
                            .eq("cab_code",storageInventoryInoutDetailForm.getCabCode())
                            .eq("code",storageInventoryInoutDetailForm.getSpaceCode()));
                    if (lanes.size()==0){
                        throw new BusinessException("未找到货道");
                    }
                    List<StorageInventorySpace> spaceInventorySpaceList= inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>()
                            .eq("cab_code",storageInventoryInoutDetailForm.getCabCode())
                            .eq("space_code",storageInventoryInoutDetailForm.getSpaceCode()));
                    if (spaceInventorySpaceList.size()>0){
                        if (spaceInventorySpaceList.get(0).getQuantity()!=null
                                &&spaceInventorySpaceList.get(0).getQuantity()>0
                                &&!spaceInventorySpaceList.get(0).getSkuCode().equals(storageInventoryInoutDetailForm.getSkuCode())){
                            throw new BusinessException("此货位已经存放了SKU编码:["+spaceInventorySpaceList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+storageInventoryInoutDetailForm.getSkuCode()+"]的刀具");
                        }

                        if (spaceInventorySpaceList.get(0).getQuantity()!=null
                                &&spaceInventorySpaceList.get(0).getQuantity()>0
                                &&spaceInventorySpaceList.get(0).getSkuCode().equals(storageInventoryInoutDetailForm.getSkuCode())
                                &&(storageInventoryInoutDetailForm.getQuantityPackUnit()!=null&&!storageInventoryInoutDetailForm.getQuantityPackUnit().equals(spaceInventorySpaceList.get(0).getQuantityPackUnit()))){
                            throw new BusinessException("此货位已经存放了包装规格数量:["+spaceInventorySpaceList.get(0).getQuantityPackUnit()+"]的刀具,"+"不可以在存放包装规格数量:["+storageInventoryInoutDetailForm.getQuantityPackUnit()+"]的刀具");
                        }
                        Integer laneQuantity=lanes.get(0).getQuantity();
                        Integer inventoryQuantity = spaceInventorySpaceList.get(0).getQuantity();
                        Integer surplusQuantity = laneQuantity-inventoryQuantity;
                        if (surplusQuantity.intValue()<storageInventoryInoutDetailForm.getQuantity().intValue()){
                            throw new BusinessException("此货道剩余可上货数不够");
                        }
                    }
                    Integer quantity = storageInventoryInoutDetailForm.getQuantity();
                    if (quantity <= 0){
                        throw new BusinessException("上货数量参数异常");
                    }
                    // 用户暂存柜产品货道库存
                    /**
                    StorageInventoryUser storageInventoryUser = new StorageInventoryUser();
                    storageInventoryUser.setCabCode(storageInventoryInoutDetailForm.getCabCode());
                    storageInventoryUser.setSpaceCode(storageInventoryInoutDetailForm.getSpaceCode());
                    storageInventoryUser.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                    storageInventoryUser.setQuantity(storageInventoryInoutDetailForm.getQuantity());
                    storageInventoryUser.setBusinessType(StorageInventoryUser.BusinessType.exhibit);
                    storageInventoryUser.setCreator(JwtUtils.getLoginUserId());
                    storageInventoryUser.setCreatorName(JwtUtils.getLoginUsername());
                    storageInventoryUser.setCompanyId(enterpriseId);
                    storageInventoryUser.setEnterpriseCode(enterpriseCode);
                    inventoryUserService.save(storageInventoryUser);*/
                    // 添加暂存柜产品货道库存
                    if(spaceSkuList.size()==0){
                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setQuantity(quantity);
                        storageInventorySpace.setCabCode(storageInventoryInoutDetailForm.getCabCode());
                        storageInventorySpace.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                        storageInventorySpace.setSpaceCode(storageInventoryInoutDetailForm.getSpaceCode());
                        storageInventorySpace.setQuantity(quantity);
                        storageInventorySpace.setCompanyId(enterpriseId);
                        storageInventorySpace.setEnterpriseCode(enterpriseCode);
                        storageInventorySpace.setLoadingType(StorageInventorySpace.LoadingType.grid);
                        storageInventorySpace.setBusinessType(StorageInventorySpace.BusinessType.exhibit);
                        storageInventorySpace.setQuantityPackUnit(quantityPackUnit);
                        storageInventorySpace.setQuantityPack(quantityPack);
                        storageInventorySpace.setPackId(storageInventoryInoutDetailForm.getPackId());
                        storageInventorySpace.setPackName(storageInventoryInoutDetailForm.getPackName());
                        storageInventorySpace.setUnitName(storageInventoryInoutDetailForm.getUnitName());
                        storageInventorySpace.setChannelCode(channelCode);
                        storageInventorySpace.setMainCabCode(mainCabCode);
                        inventorySpaceService.save(storageInventorySpace);
                        storageInventoryInoutDetail.setQuantityCurrent(0);
                        storageInventoryInoutDetail.setQuantityAfter(quantity);
                        storageInventoryInoutDetail.setQuantity(quantity);
                        storageInventoryInoutDetail.setQuantityPackCurrent(0);
                        storageInventoryInoutDetail.setQuantityPackAfter(quantityPack);
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }else{
                        Integer currentQuantity=spaceSkuList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+quantity;
                        StorageInventorySpace storageInventorySpace = new StorageInventorySpace();
                        storageInventorySpace.setId(spaceSkuList.get(0).getId());
                        storageInventorySpace.setQuantity(newQuantity);
                        if (spaceSkuList.get(0).getQuantity()==0){
                            storageInventorySpace.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                        }
                        storageInventorySpace.setPackName(storageInventoryInoutDetailForm.getPackName());
                        storageInventorySpace.setPackId(storageInventoryInoutDetailForm.getPackId());
                        storageInventorySpace.setUnitName(storageInventoryInoutDetailForm.getUnitName());

//                        if (quantityPack!=null){
                        Integer currentQuantityPack=spaceSkuList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventorySpace.setQuantityPack(currentQuantityPack+quantityPack);
                        storageInventorySpace.setQuantityPackUnit(quantityPackUnit);
//                        }
                        inventorySpaceService.updateById(storageInventorySpace);
                        storageInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        storageInventoryInoutDetail.setQuantityAfter(newQuantity);
                        storageInventoryInoutDetail.setQuantity(quantity);
                        storageInventoryInoutDetail.setQuantityPackCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackAfter(storageInventorySpace.getQuantityPack());
//                        baseMapper.insert(storageInventoryInoutDetail);
                    }
                    // 添加售刀柜sku库存(某个柜子)
                    if(skuSingleInventoryList.size()==0){
                        StorageSingleInventoryProduct storageSingleInventoryProduct = new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setCabCode(storageInventoryInoutDetailForm.getCabCode());
                        storageSingleInventoryProduct.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(quantity);
                        storageSingleInventoryProduct.setCompanyId(enterpriseId);
                        storageSingleInventoryProduct.setEnterpriseCode(enterpriseCode);
                        storageSingleInventoryProduct.setBusinessType(StorageSingleInventoryProduct.BusinessType.exhibit);
                        storageSingleInventoryProduct.setQuantityPackUnit(quantityPackUnit);
                        storageSingleInventoryProduct.setQuantityPack(quantityPack);
                        storageSingleInventoryProduct.setPackId(packId);
                        storageSingleInventoryProduct.setPackName(storageInventoryInoutDetailForm.getPackName());
                        storageSingleInventoryProduct.setUnitName(storageInventoryInoutDetailForm.getUnitName());
                        storageSingleInventoryProduct.setChannelCode(channelCode);
                        storageSingleInventoryProduct.setMainCabCode(mainCabCode);
                        storageSingleInventoryProduct.setCreator(JwtUtils.getLoginUserId());
                        storageSingleInventoryProduct.setCreatorName(JwtUtils.getLoginUsername());
                        storageSingleInventoryProductService.save(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(0);
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackSingleCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityPackSingleCabAfter(storageSingleInventoryProduct.getQuantityPack());
                    }else{
                        StorageSingleInventoryProduct storageSingleInventoryProduct= new StorageSingleInventoryProduct();
                        storageSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
                        storageSingleInventoryProduct.setCabCode(storageInventoryInoutDetailForm.getCabCode());
                        storageSingleInventoryProduct.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                        storageSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity()+quantity);
                        storageSingleInventoryProduct.setPackId(packId);
                        storageSingleInventoryProduct.setPackName(storageInventoryInoutDetailForm.getPackName());
                        storageSingleInventoryProduct.setPackId(storageInventoryInoutDetailForm.getPackId());
                        storageSingleInventoryProduct.setUnitName(storageInventoryInoutDetailForm.getUnitName());
//                        if (quantityPack!=null){
                        Integer currentQuantityPack=skuSingleInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageSingleInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        storageSingleInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                        }
                        storageSingleInventoryProductService.updateById(storageSingleInventoryProduct);

                        storageInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantitySingleCabAfter(storageSingleInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackSingleCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackSingleCabAfter(currentQuantityPack+quantityPack);
                    }
                    // 添加暂存柜产品库存
                    if (skuInventoryList.size()==0){
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(quantity);
                        storageInventoryProduct.setCompanyId(enterpriseId);
                        storageInventoryProduct.setEnterpriseCode(enterpriseCode);
                        storageInventoryProduct.setBusinessType(StorageInventoryProduct.BusinessType.exhibit);
                        storageInventoryProduct.setQuantityPackUnit(quantityPackUnit);
                        storageInventoryProduct.setQuantityPack(quantityPack);
                        storageInventoryProduct.setPackId(packId);
                        storageInventoryProduct.setPackName(storageInventoryInoutDetailForm.getPackName());
                        storageInventoryProduct.setUnitName(storageInventoryInoutDetailForm.getUnitName());
                        storageInventoryProduct.setChannelCode(channelCode);
                        inventoryProductService.save(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackCabCurrent(0);
                        storageInventoryInoutDetail.setQuantityPackCabAfter(quantityPack);
                    }else{
                        StorageInventoryProduct storageInventoryProduct = new StorageInventoryProduct();
                        storageInventoryProduct.setId(skuInventoryList.get(0).getId());
                        storageInventoryProduct.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
                        storageInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity()+quantity);
                        storageInventoryProduct.setPackName(storageInventoryInoutDetailForm.getPackName());
                        storageInventoryProduct.setPackId(storageInventoryInoutDetailForm.getPackId());
                        storageInventoryProduct.setUnitName(storageInventoryInoutDetailForm.getUnitName());
//                        if (quantityPack!=null){
                        Integer currentQuantityPack=skuInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        storageInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        storageInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                        }
                        inventoryProductService.updateById(storageInventoryProduct);

                        storageInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        storageInventoryInoutDetail.setQuantityCabAfter(storageInventoryProduct.getQuantity());
                        storageInventoryInoutDetail.setQuantityPackCabCurrent(currentQuantityPack);
                        storageInventoryInoutDetail.setQuantityPackCabAfter(currentQuantityPack+quantityPack);
                    }

                    //上货时查询产品物料表产品包装条码 是否 存在，不存在，反写
                    //if(null == productDetail.getPackId()){
                    productDetail.setPackId(storageInventoryInoutDetailForm.getPackId());
                    productDetail.setBasePrice(new BigDecimal(1));
                    ProductPack productPack = productPackService.getById(storageInventoryInoutDetailForm.getPackId());
                    if(null != productPack) {
                        productDetail.setUnitId(productPack.getProductUnitId());
                        if(null != productDetail.getMarketPrice()) {
                            productDetail.setBasePrice(productDetail.getMarketPrice().divide(new BigDecimal(productPack.getBaseRate()),2, RoundingMode.HALF_UP));
                        }
                    }
                    productDetailService.updateById(productDetail);
                    //}
//                    baseMapper.insert(storageInventoryInoutDetail);
                    // 刀具编号
//                    for (int i = 0; i < storageInventoryInoutDetailForm.getQuantity(); i++) {
//                        UseInventoryUserKnifeSeq useInventoryUserKnifeSeq = new UseInventoryUserKnifeSeq();
//                        useInventoryUserKnifeSeqService.insert(useInventoryUserKnifeSeq);
//                        Long labelId = useInventoryUserKnifeSeqService.getId();
//                        String labelCode = StringUtils.leftPad(labelId.toString(), 10, "0");
//                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
//                        useInventoryUserKnife.setCode(labelCode);
//                        useInventoryUserKnife.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
//                        useInventoryUserKnife.setUseInventoryInoutId(inventoryInoutId);
//                        useInventoryUserKnife.setCreator(JwtUtils.getLoginUserId());
//                        useInventoryUserKnife.setCreatorName(JwtUtils.getLoginUsername());
//                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.latticeCabinetBatchUp);
//                        useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
//                        useInventoryUserKnife.setEnterpriseCode(enterpriseCode);
//                        useInventoryUserKnife.setCabCode(storageInventoryInoutDetailForm.getCabCode());
//                        useInventoryUserKnife.setSpaceCode(storageInventoryInoutDetailForm.getSpaceCode());
//                        useInventoryUserKnife.setInTime(LocalDateTime.now());
//                        useInventoryUserKnife.setLoadingType(UseInventoryUserKnife.LoadingType.grid);
//                        StorageInventoryKnife storageInventoryKnife = new StorageInventoryKnife();
//                        if (productDetails.size() > 0) {
//                            if (productDetails.get(0).getLifeSpan() != null) {
//                                if (productDetails.get(0).getLifeSpan() != null) {
//                                   // useInventoryUserKnife.setInitTime(productDetails.get(0).getLifeSpan());
//                                   // useInventoryUserKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
//                                    storageInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
//                                }
//                                if (productDetails.get(0).getLifeUnit() != null) {
//                                   // useInventoryUserKnife.setLifeUnit(UseInventoryUserKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
//                                    storageInventoryKnife.setLifeUnit(StorageInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
//                                }
//                            }
//                        }
//                        //useInventoryUserKnifeService.save(useInventoryUserKnife);
//                        // 添加刀具产品货道库存
//                        storageInventoryKnife.setCabCode(storageInventoryInoutDetailForm.getCabCode());
//                        storageInventoryKnife.setSpaceCode(storageInventoryInoutDetailForm.getSpaceCode());
//                        storageInventoryKnife.setSkuCode(storageInventoryInoutDetailForm.getSkuCode());
//                        storageInventoryKnife.setQuantity(storageInventoryInoutDetailForm.getQuantity());
//                        storageInventoryKnife.setBusinessType(StorageInventoryKnife.BusinessType.exhibit);
//                        storageInventoryKnife.setCreator(JwtUtils.getLoginUserId());
//                        storageInventoryKnife.setCreatorName(JwtUtils.getLoginUsername());
//                        storageInventoryKnife.setCompanyId(enterpriseId);
//                        storageInventoryKnife.setDeviceCode(labelCode);
//                        storageInventoryKnife.setLabelCode(storageInventoryInoutDetailForm.getLabelCode());
//                        storageInventoryKnife.setStorageInventoryInoutId(inventoryInoutId);
//                        storageInventoryKnife.setStorageInventoryUserId(useInventoryUserKnife.getId());
//                        storageInventoryKnife.setEnterpriseCode(enterpriseCode);
//                        storageInventoryKnife.setBusinessDetailType(StorageInventoryKnife.BusinessDetailType.latticeCabinetBatchUp);
//                        storageInventoryKnife.setRemark(storageInventoryKnife.getBusinessDetailTypeDesc());
//                        storageInventoryKnife.setInTime(LocalDateTime.now());
//                        storageInventoryKnife.setLoadingType(StorageInventoryKnife.LoadingType.grid);
//                        storageInventoryKnifeService.save(storageInventoryKnife);
//                    }

                }
                BigDecimal price=null;
                BigDecimal total=null;
                Long packId=null;
                if (null != productDetail && productDetail.getMarketPrice()!=null){
//                    quantityPackUnit=productDetails.get(0).getUnitRate();
//                    if (quantityPackUnit!=null){
//                        quantityPack=cellInventoryInoutDetailForm.getQuantity()*quantityPackUnit;
//                    }
//                    packId=productDetails.get(0).getPackId();
                    price = productDetail.getMarketPrice();
                    if (price!=null){
                        total=price.multiply(BigDecimal.valueOf(Math.abs(quantityPack)));
                    }
                }
                storageInventoryInoutDetail.setPrice(price);
                storageInventoryInoutDetail.setTotal(total);
                storageInventoryInoutDetail.setQuantityPack(quantityPack);
                storageInventoryInoutDetail.setQuantityPackUnit(quantityPackUnit);
                storageInventoryInoutDetailForm.setPrice(price);
                storageInventoryInoutDetailForm.setTotal(total);
                storageInventoryInoutDetailForm.setQuantityPack(quantityPack);
                storageInventoryInoutDetailForm.setQuantityPackUnit(quantityPackUnit);
                baseMapper.insert(storageInventoryInoutDetail);
            }
        }else{
            throw new BusinessException("未提交领用刀具数据");
        }
    }

    @Override
    public StorageInventoryInout latticeCabinetUnload(OrderReceiveLoadForm orderReceiveLoadForm) {
        List<OrderReceiveLoadDetailForm> detailList=new ArrayList<>();
        OrderReceiveLoadDetailForm orderReceiveLoadDetailForm=new OrderReceiveLoadDetailForm();
        orderReceiveLoadDetailForm.setCabCode(orderReceiveLoadForm.getCabCode());
        orderReceiveLoadDetailForm.setSkuCode(orderReceiveLoadForm.getSkuCode());
        orderReceiveLoadDetailForm.setSpaceCode(orderReceiveLoadForm.getSpaceCode());
        orderReceiveLoadDetailForm.setQuantity(orderReceiveLoadForm.getQuantity());
        detailList.add(orderReceiveLoadDetailForm);
        orderReceiveLoadForm.setDetailList(detailList);
        return this.inventoryOut4BatchSimple(orderReceiveLoadForm);
    }

    private StorageInventoryInout inventoryOut4BatchSimple(OrderReceiveLoadForm orderReceiveLoadForm) {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        String channelCode = JwtUtils.getChannelCode();
        String roleName = JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        StorageInventoryInoutForm storageInventoryInoutForm = new StorageInventoryInoutForm();
        List<StorageInventoryInoutDetailForm> list = new ArrayList<>();
        for(OrderReceiveLoadDetailForm orderReceiveLoadDetailForm:orderReceiveLoadForm.getDetailList()){
            StorageInventoryInoutDetailForm storageInventoryInoutDetailForm = new StorageInventoryInoutDetailForm();
            storageInventoryInoutDetailForm.setCabCode(orderReceiveLoadDetailForm.getCabCode());
            storageInventoryInoutDetailForm.setSkuCode(orderReceiveLoadDetailForm.getSkuCode());
            storageInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadDetailForm.getSpaceCode());
            storageInventoryInoutDetailForm.setQuantity(orderReceiveLoadDetailForm.getQuantity());
            List<StorageInventorySpace> cellInventorySpaces=inventorySpaceService.list(new QueryWrapper<StorageInventorySpace>().eq("cab_code",orderReceiveLoadDetailForm.getCabCode()).eq("space_code",orderReceiveLoadDetailForm.getSpaceCode()));
            if (cellInventorySpaces.size()>0){
                storageInventoryInoutDetailForm.setQuantityPackUnit(cellInventorySpaces.get(0).getQuantityPackUnit());
                if (storageInventoryInoutDetailForm.getQuantityPackUnit()==null){
                    storageInventoryInoutDetailForm.setQuantityPackUnit(1);
                }
                storageInventoryInoutDetailForm.setPackName(cellInventorySpaces.get(0).getPackName());
                storageInventoryInoutDetailForm.setPackId(cellInventorySpaces.get(0).getPackId());
                storageInventoryInoutDetailForm.setUnitName(cellInventorySpaces.get(0).getUnitName());
                orderReceiveLoadDetailForm.setQuantityPackUnit(storageInventoryInoutDetailForm.getQuantityPackUnit());
                orderReceiveLoadDetailForm.setPackName(storageInventoryInoutDetailForm.getPackName());
                orderReceiveLoadDetailForm.setPackId(storageInventoryInoutDetailForm.getPackId());
                orderReceiveLoadDetailForm.setUnitName(storageInventoryInoutDetailForm.getUnitName());

                orderReceiveLoadDetailForm.setQuantityPack(storageInventoryInoutDetailForm.getQuantityPackUnit()*orderReceiveLoadDetailForm.getQuantity());
            }
            list.add(storageInventoryInoutDetailForm);
        }
        storageInventoryInoutForm.setDetailList(list);
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        String code=dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("OU-"+day+"-"+code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(JwtUtils.getLoginUserId());
        storageInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.out);
        storageInventoryInout.setBusinessType(StorageInventoryInout.BusinessType.unload);
        storageInventoryInout.setBusinessDetailType(StorageInventoryInout.BusinessDetailType.unload);
        storageInventoryInout.setCompanyId(enterpriseId);
        storageInventoryInout.setEnterpriseCode(enterpriseCode);
        storageInventoryInout.setRemark(StorageInventoryInout.BusinessDetailType.unload.getDesc());
        storageInventoryInout.setTotal(getTotal2(list));
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setDepartmentName(departmentName);
        storageInventoryInout.setRoleId(roleId);
        storageInventoryInout.setRoleName(roleName);
        storageInventoryInout.setChannelCode(channelCode);
        inventoryInoutService.save(storageInventoryInout);
        OrderReceiveLoad orderReceiveLoad=new OrderReceiveLoad();
        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoad);
        code=dynamicService.getDayNextCode("ord_order_receive_load");
        orderReceiveLoad.setCode("GZ-"+day+"-"+code);
        orderReceiveLoad.setDay(Integer.valueOf(day));
        orderReceiveLoad.setNo(Integer.valueOf(code));
        orderReceiveLoad.setCreator(JwtUtils.getLoginUserId());
        orderReceiveLoad.setCreatorName(JwtUtils.getLoginUsername());
        orderReceiveLoad.setType(OrderReceiveLoad.Type.selfUnloadSimple);
        orderReceiveLoadService.save(orderReceiveLoad);
        saveReceiveLoadDetail(orderReceiveLoadForm,orderReceiveLoad.getId());
        saveLatticeCabinetDetail(list,storageInventoryInout.getId(),StorageInventoryInout.OperationType.out.name());
        return storageInventoryInout;
    }

    @Override
    @Transactional
    public StorageInventoryInout xgzInventoryRepairIn(UseInventoryInoutForm useInventoryInoutForm, StorageInventoryInout.BusinessType businessType
            , StorageInventoryInout.BusinessDetailType businessDetailType) {
        List<UseInventoryInoutDetailForm> list = useInventoryInoutForm.getDetailList();
        /**
         * 小柜子选择存刀货道，小柜子的存刀只有二个格子，一个存报废，一个存报修
         */
        QueryWrapper<Cabinet> cabQueryWrapper = new QueryWrapper();
        cabQueryWrapper.eq("belong_cabinet", useInventoryInoutForm.getMainCabCode());
        cabQueryWrapper.eq("cabinet_nature", Cabinet.CabinetNature.live.getValue());
        List<Cabinet> strongeCabList = cabinetService.list(cabQueryWrapper);
        if(null == strongeCabList || strongeCabList.size() == 0){
            throw new BusinessException("格子柜不存在");
        }
        String cabCodes = strongeCabList.stream().map(Cabinet::getCode).collect(Collectors.joining(","));
        List<String> skuCodes = list.stream().map(e -> e.getSkuCode()).collect(Collectors.toList());
        CabinetCargoSpaceVO spaceVO = this.getSpaces(CabinetCargoSpace.SpaceNature.repair,cabCodes,skuCodes, StorageInventoryInout.BusinessType.repair,1);
        if(null == spaceVO){
            throw new BusinessException("未找到可用的格子");
        }
        for(UseInventoryInoutDetailForm useInventoryInoutDetailForm : list){
            useInventoryInoutDetailForm.setCabCode(spaceVO.getCabCode());
            useInventoryInoutDetailForm.setSpaceCode(spaceVO.getCode());
        }

        String deviceCode = useInventoryInoutForm.getDeviceCode();
        String remark = useInventoryInoutForm.getRemark();
        if (StringUtils.isBlank(deviceCode)){
            deviceCode=list.get(0).getDeviceCode();
        }

        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long departmentId = JwtUtils.getDepartmentId();
        String departmentName = JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        String channelCode=JwtUtils.getChannelCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        String code = dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("IN-" + day + "-" + code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(JwtUtils.getLoginUserId());
        storageInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        storageInventoryInout.setCostCenter(JwtUtils.getCostCenter());
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.in);
        storageInventoryInout.setBusinessType(businessType);
        storageInventoryInout.setCompanyId(enterpriseId);
        storageInventoryInout.setDeviceCode(deviceCode);
        storageInventoryInout.setBusinessDetailType(businessDetailType);
        storageInventoryInout.setRemark(remark);
        if (StringUtils.isNotBlank(list.get(0).getRemark())){
            storageInventoryInout.setRemark(list.get(0).getRemark());
        }else{
            storageInventoryInout.setRemark(businessDetailType.getDesc());
        }
        storageInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        storageInventoryInout.setProcessId(list.get(0).getProcessId());
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setDepartmentName(departmentName);
        storageInventoryInout.setRoleName(roleName);
        storageInventoryInout.setEnterpriseCode(enterpriseCode);
        storageInventoryInout.setTotal(getTotal(list,storageInventoryInout.getOperationType()));
        storageInventoryInout.setChannelCode(channelCode);
        storageInventoryInout.setRoleId(roleId);
        storageInventoryInout.setMainCabCode(useInventoryInoutForm.getMainCabCode());
        inventoryInoutService.save(storageInventoryInout);
        saveDetail(list, storageInventoryInout.getId(), UseInventoryInout.Type.in.name(), businessType, false, deviceCode, businessDetailType, null, null, null);
        useInventoryInoutDetailService.inventoryOut(list, storageInventoryInout.getId(), deviceCode, businessType, UseInventoryInout.Type.out, businessDetailType,remark);

        List<String> labelCodeList = new ArrayList<>();
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
            labelCodeList.add(useInventoryInoutDetailForm.getLabelCode());
        }
        // 添加刀具生命周期  --  暂存存入
        CutterLifeCycle.Status cutterLifeCycleStatus = null;
        if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempIn)){ // 暂存
            cutterLifeCycleStatus = CutterLifeCycle.Status.temporaryStorage;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairIn)){ // 报修
            cutterLifeCycleStatus = CutterLifeCycle.Status.repair;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleIn)){ // 报废
            cutterLifeCycleStatus = CutterLifeCycle.Status.scrap;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempInByOldNew)
                || businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairInByOldNew)
                || businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleInByOldNew)){ // 以旧换新
            cutterLifeCycleStatus = CutterLifeCycle.Status.tradeIn;
        }
        if(cutterLifeCycleStatus != null){
            cutterLifeCycleService.addLifeCycle(labelCodeList, cutterLifeCycleStatus, businessDetailType, null, storageInventoryInout.getCode(), deviceCode);
        }

//        StorageInventoryUncheck storageInventoryUncheck=new StorageInventoryUncheck();
//        storageInventoryUncheck.setInoutId(storageInventoryInout.getId());
//        inventoryUncheckService.save(storageInventoryUncheck);
        sendMsg(storageInventoryInout);
        return storageInventoryInout;
    }


    @Override
    @Transactional
    public StorageInventoryInout xgzInventoryRecycleIn(UseInventoryInoutForm useInventoryInoutForm, StorageInventoryInout.BusinessType businessType
            , StorageInventoryInout.BusinessDetailType businessDetailType) {
        List<UseInventoryInoutDetailForm> list = useInventoryInoutForm.getDetailList();
        /**
         * 小柜子选择存刀货道，小柜子的存刀只有二个格子，一个存报废，一个存报修
         */
        QueryWrapper<Cabinet> cabQueryWrapper = new QueryWrapper();
        cabQueryWrapper.eq("belong_cabinet", useInventoryInoutForm.getMainCabCode());
        cabQueryWrapper.eq("cabinet_nature", Cabinet.CabinetNature.live.getValue());
        List<Cabinet> strongeCabList = cabinetService.list(cabQueryWrapper);
        if(null == strongeCabList || strongeCabList.size() == 0){
            throw new BusinessException("格子柜不存在");
        }
        String cabCodes = strongeCabList.stream().map(Cabinet::getCode).collect(Collectors.joining(","));
        List<String> skuCodes = list.stream().map(e -> e.getSkuCode()).collect(Collectors.toList());
        CabinetCargoSpaceVO spaceVO = this.getSpaces(CabinetCargoSpace.SpaceNature.recycle,cabCodes,skuCodes, StorageInventoryInout.BusinessType.recycle,1);
        if(null == spaceVO){
            throw new BusinessException("未找到可用的格子");
        }
        for(UseInventoryInoutDetailForm useInventoryInoutDetailForm : list){
            useInventoryInoutDetailForm.setCabCode(spaceVO.getCabCode());
            useInventoryInoutDetailForm.setSpaceCode(spaceVO.getCode());
        }

        String deviceCode = useInventoryInoutForm.getDeviceCode();
        String remark = useInventoryInoutForm.getRemark();
        if (StringUtils.isBlank(deviceCode)){
            deviceCode=list.get(0).getDeviceCode();
        }

        Long enterpriseId = JwtUtils.getEnterpriseId();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long departmentId = JwtUtils.getDepartmentId();
        String departmentName = JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        String channelCode=JwtUtils.getChannelCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        StorageInventoryInout storageInventoryInout = new StorageInventoryInout();
        String code = dynamicService.getDayNextCode("cab_storage_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        storageInventoryInout.setCode("IN-" + day + "-" + code);
        storageInventoryInout.setDay(Integer.valueOf(day));
        storageInventoryInout.setNo(Integer.valueOf(code));
        storageInventoryInout.setCreator(JwtUtils.getLoginUserId());
        storageInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        storageInventoryInout.setCostCenter(JwtUtils.getCostCenter());
        storageInventoryInout.setOperationType(StorageInventoryInout.OperationType.in);
        storageInventoryInout.setBusinessType(businessType);
        storageInventoryInout.setCompanyId(enterpriseId);
        storageInventoryInout.setDeviceCode(deviceCode);
        storageInventoryInout.setBusinessDetailType(businessDetailType);
        storageInventoryInout.setRemark(remark);
        if (StringUtils.isNotBlank(list.get(0).getRemark())){
            storageInventoryInout.setRemark(list.get(0).getRemark());
        }else{
            storageInventoryInout.setRemark(businessDetailType.getDesc());
        }
        storageInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        storageInventoryInout.setProcessId(list.get(0).getProcessId());
        storageInventoryInout.setDepartmentId(departmentId);
        storageInventoryInout.setDepartmentName(departmentName);
        storageInventoryInout.setRoleName(roleName);
        storageInventoryInout.setEnterpriseCode(enterpriseCode);
        storageInventoryInout.setTotal(getTotal(list,storageInventoryInout.getOperationType()));
        storageInventoryInout.setChannelCode(channelCode);
        storageInventoryInout.setRoleId(roleId);
        storageInventoryInout.setMainCabCode(useInventoryInoutForm.getMainCabCode());
        inventoryInoutService.save(storageInventoryInout);
        saveDetail(list, storageInventoryInout.getId(), UseInventoryInout.Type.in.name(), businessType, false, deviceCode, businessDetailType, null, null, null);
        useInventoryInoutDetailService.inventoryOut(list, storageInventoryInout.getId(), deviceCode, businessType, UseInventoryInout.Type.out, businessDetailType,remark);

        List<String> labelCodeList = new ArrayList<>();
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
            labelCodeList.add(useInventoryInoutDetailForm.getLabelCode());
        }
        // 添加刀具生命周期  --  暂存存入
        CutterLifeCycle.Status cutterLifeCycleStatus = null;
        if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempIn)){ // 暂存
            cutterLifeCycleStatus = CutterLifeCycle.Status.temporaryStorage;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairIn)){ // 报修
            cutterLifeCycleStatus = CutterLifeCycle.Status.repair;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleIn)){ // 报废
            cutterLifeCycleStatus = CutterLifeCycle.Status.scrap;
        }else if(businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempInByOldNew)
                || businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairInByOldNew)
                || businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleInByOldNew)){ // 以旧换新
            cutterLifeCycleStatus = CutterLifeCycle.Status.tradeIn;
        }
        if(cutterLifeCycleStatus != null){
            cutterLifeCycleService.addLifeCycle(labelCodeList, cutterLifeCycleStatus, businessDetailType, null, storageInventoryInout.getCode(), deviceCode);
        }

//        StorageInventoryUncheck storageInventoryUncheck=new StorageInventoryUncheck();
//        storageInventoryUncheck.setInoutId(storageInventoryInout.getId());
//        inventoryUncheckService.save(storageInventoryUncheck);
        sendMsg(storageInventoryInout);
        return storageInventoryInout;
    }


}
